我对以下代码有疑问:
public Class Settings{
public static final String WelcomeMessage= "helloworld";
public static final String ByeMessage= "yo";
public static String[] widgets = {WelcomeMessage,ByeMessage};
}
编译器抱怨重复变量。我可以删除2个单独的变量,并且仍然可以通过Settings.WelcomeMessage访问WelcomeMessage吗?我不需要通过Settings.widget [0]访问吗?是否可以向WelcomeMessage变量添加另一个变量(例如,使用静态哈希表)?
编辑:我知道这段代码看起来不正确,但这只是一个示例,因为我想知道为什么编译器认为WelcomeMessage(作为separata变量)与Widgets数组中的变量相同。
最佳答案
我会在您的情况下考虑Java枚举:
public enum Settings {
WelcomeMessage ("helloworld"),
ByeMessage ("yo");
public final String value;
Settings(String value) {
this.value = value;
}
}
您现在可以通过
Settings.WelcomeMessage.value
访问值。您还可以通过Settings.values()
获得枚举列表。关于java - 重复的静态字段(数组与字符串),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4955927/