如何在Java中存储字符串的常量数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9777958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:33:55  来源:igfitidea点击:

How to store constant array of string in Java

javaenumsconst

提问by tsusanka

I am choosing randomly from set of particular strings in my application. I store those data in the code directly. As far as I know, you can't declare public static final String[] = {"aa", "bb"}. So I though the enum would be useful, which works fine with one-word names:

我从应用程序中的一组特定字符串中随机选择。我直接将这些数据存储在代码中。据我所知,你不能声明public static final String[] = {"aa", "bb"}. 所以我认为 enum 会很有用,它适用于单字名称:

public enum NAMES {
  Mike, Peter, Tom, Andy
}

But how do I store sentences like this? Here the enum fails:

但是我如何存储这样的句子?这里枚举失败:

public enum SECRETS {
  "George Tupou V, the King of Tonga, dies in Hong Kong at the age of 63.",
  "Joachim Gauck is elected President of Germany.",
  "Lindsey Vonn and Marcel Hirscher win the Alpine Skiing World Cup.";
}

What else should I use? Or am I using the enum incorrectly?

我还应该使用什么?还是我错误地使用了枚举?

采纳答案by Matt Ball

public enum Secret
{
    TONGA("George Tupou V, the King of Tonga, dies in Hong Kong at the age of 63."), 
    GERMANY("Joachim Gauck is elected President of Germany."),
    SKIING("Lindsey Vonn and Marcel Hirscher win the Alpine Skiing World Cup.");

    private final String message;

    private Secret(String message)
    {
        this.message = message;
    }

    public String getMessage()
    {
        return this.message;
    }
}

回答by Jon Skeet

You can't create an immutable array, basically. The closest you can come is to create an immutable collection, e.g. with Guava.

基本上,您无法创建不可变数组。最接近的是创建一个不可变的集合,例如使用Guava

public static final ImmutableList<String> SECRETS = ImmutableList.of(
    "George Tupou V, the King of Tonga, dies in Hong Kong at the age of 63.", 
    "Joachim Gauck is elected President of Germany.",
    "Lindsey Vonn and Marcel Hirscher win the Alpine Skiing World Cup.");

You coulduse an enumby giving each enum value an associated string, like this:

可以enum通过为每个枚举值提供一个关联的字符串使用 an ,如下所示:

public enum Secret {
    SECRET_0("George..."),
    SECRET_1("Joachim..."),
    SECRET_2("Lindsey...");

    private final String text;

    private Secret(String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}

... but if you justwant the strings as a collection, I'd use the immutable list. Enums are great when they're appropriate, but there's no indication that they're really appropriate in this case.

...但如果你想要字符串作为一个集合,我会使用不可变列表。枚举在合适时很棒,但没有迹象表明它们在这种情况下真的合适。

EDIT: As noted in another answer, this isperfectly valid:

编辑:如另一个答案所述,这完全有效的:

public static final String[] FOO = {"aa", "bb"};

... assuming it's not in an inner class (which you didn't mention anywhere in your question). However, it's a very bad ideaas arrays are always mutable. It's not a "constant" array; the referencecan't be changed, but other code could write:

...假设它不在内部类中(您没有在问题中的任何地方提及)。然而,这是一个非常糟糕的主意,因为数组总是可变的。它不是一个“常量”数组;该参考无法改变,但其他的代码可以这样写:

WhateverYourTypeIs.FOO[0] = "some other value";

... which I suspect you don't want.

...我怀疑你不想要。

回答by Jakub Zaverka

You can do

你可以做

public static final String[] = {"aa", "bb"};

you just need to specify the name of the field:

您只需要指定字段的名称:

public static final String[] STRINGS = {"aa", "bb"};

EDIT: I second Jon Skeet's answer that this is bad code practice. Anybody can then modify the contents of your array. What you can do is declare it private and specify a getter for the array. You will preserve the index-access and prevent accidental writes:

编辑:我支持 Jon Skeet 的回答,即这是糟糕的代码实践。然后任何人都可以修改数组的内容。您可以做的是将其声明为私有并为数组指定一个 getter。您将保留索引访问并防止意外写入:

private static final String[] STRINGS = {"aa", "bb"};

public static String getString(int index){
    return STRINGS[index];
}

I guess you would need a method to get the length of the array as well:

我想您还需要一种方法来获取数组的长度:

public static int stringCount(){
    return STRINGS.length;
}

But as long as your project is small and you know what you are doing, you will be perfectly fine just leaving it public.

但是只要您的项目很小并且您知道自己在做什么,只要将其公开就可以了。

回答by Thomas

public enum NAMES {

  Mike("Mike Smith"),
  Peter("Peter Jones"),
  Tom("Thomas White"),
  Andy("Andrew Chu");

  private final String fullname;

  private NAMES(String value)
  {
    fullname = value;
  }
};

回答by nicobn

Insert the selected sentences in a Set<String>and then use the return value of Collections.unmodifiableSet(). Example:

将选中的句子插入到 a 中Set<String>,然后使用 的返回值Collections.unmodifiableSet()。例子:

final Set<String> mutableSentences = new HashSet<>();
/* ... */
final Set<String> sentences = Collections.unmodifiableSet(mutableSentences);