我在我的应用程序中从一组特定字符串中随机选择.我将这些数据直接存储在代码中.据我所知,你无法申报public static final String[] = {"aa", "bb"}
.所以我虽然enum会很有用,但对于单字名称可以正常工作:
public enum NAMES {
Mike, Peter, Tom, Andy
}
Run Code Online (Sandbox Code Playgroud)
但是如何存储这样的句子呢?这里的枚举失败了:
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.";
}
Run Code Online (Sandbox Code Playgroud)
我还应该使用什么?或者我错误地使用枚举?
Jak*_*rka 20
你可以做
public static final String[] = {"aa", "bb"};
Run Code Online (Sandbox Code Playgroud)
你只需要指定字段的名称:
public static final String[] STRINGS = {"aa", "bb"};
Run Code Online (Sandbox Code Playgroud)
编辑:我第二个Jon Skeet的答案,这是糟糕的代码练习.然后任何人都可以修改数组的内容.你可以做的是声明它是私有的并为数组指定一个getter.您将保留索引访问并防止意外写入:
private static final String[] STRINGS = {"aa", "bb"};
public static String getString(int index){
return STRINGS[index];
}
Run Code Online (Sandbox Code Playgroud)
我想你需要一个方法来获得数组的长度:
public static int stringCount(){
return STRINGS.length;
}
Run Code Online (Sandbox Code Playgroud)
但是只要你的项目规模很小并且你知道自己在做什么,你就可以将它公之于众.
基本上,你不能创建一个不可变数组.最接近的是创建一个不可变的集合,例如使用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.");
Run Code Online (Sandbox Code Playgroud)
你可以使用a enum
给每个枚举值一个相关的字符串,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
...但是如果你只想将字符串作为集合,我会使用不可变列表.当它们合适时,枚举很棒,但没有迹象表明它们在这种情况下非常合适.
编辑:如另一个答案所述,这是完全有效的:
public static final String[] FOO = {"aa", "bb"};
Run Code Online (Sandbox Code Playgroud)
...假设它不在内部类(你在问题的任何地方没有提到).然而,这是一个非常糟糕的主意,因为数组总是可变的.它不是一个"常数"阵列; 该参考无法改变,但其他的代码可以这样写:
WhateverYourTypeIs.FOO[0] = "some other value";
Run Code Online (Sandbox Code Playgroud)
...我怀疑你不想要的.
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;
}
}
Run Code Online (Sandbox Code Playgroud)