[英]Use a static variable or method for a constant array in Java
I'm wondering if it is better to use a final static variable or method to provide a constant array in Java. 我想知道使用最终的静态变量或方法在Java中提供常量数组是否更好。
Say we have: 说我们有:
public class myColor {
public final static String[] COLOR_NAMES = new String[] {"red", "green"};
public final static String[] colorNames() {return new String[] {"red", "green"};}
}
To me, the second one has the disadvantage that each time it's called a new String array is created. 对我来说,第二个缺点是每次创建一个新的String数组时都会创建它。 But the first one has the disadvantage, that anyone could do
COLOR_NAMES[0] = "blue"
. 但是第一个缺点是,任何人都可以做
COLOR_NAMES[0] = "blue"
。
To clarify: I specifically want to provide a list of color names for a subsequent match with regular expressions. 澄清一下:我特别想提供一个颜色名称列表,以便随后与正则表达式匹配。
Is there any established way how this is typically solved? 有什么确定的方法通常可以解决此问题吗?
You can use enum 您可以使用枚举
public enum Color{
RED("red"), GREEN("green");
final String color;
Color(String color) {
this.color=color;
}
public String getColor() {
return color;
}
}
This question is fall for using Enum
. 这个问题不适合使用
Enum
。 Personally I wont be using any method for that. 我个人不会使用任何方法。 But weather static array is good solution for that?
但是,天气静态数组是一个好的解决方案吗? It is better to solve it using java enums .
最好使用java枚举来解决。
To initialise an array at construction time you can specify a list values in curly braces: 要在构造时初始化数组,可以使用大括号指定列表值:
private static final String[] STRING_ARRAY = {"red", "green", "blue"};
In my example I have assumed that you won't want to change the instance of array and so have declared it final. 在我的示例中,我假设您不想更改array的实例,因此已将其声明为final。 You still would be able to update individual entries like so:
您仍然可以像这样更新各个条目:
array[0] = "1";
But you won't be able to replace the array with a different one completely. 但是您将无法完全用另一阵列替换该阵列。 If the values are going to change a lot - especially if the number of values are going to change - then it may be worth considering using List instead.
如果值将发生很大变化(尤其是值的数目将发生变化) ,则可能值得考虑使用List 。
If you can go with a list, one option would be: 如果可以使用列表,则可以选择以下一种方法:
public final static List<String> COLOR_NAMES = Collections.unmodifiableList(
Arrays.asList("red", "green"));
You can always get an array if needed: 如果需要,您总是可以得到一个数组:
String[] array = COLOR_NAMES.toArray(new String[0]);
Otherwise your second option is fine although I would write it: 否则,您的第二个选择就可以了,尽管我会这样写:
private final String[] COLOR_NAMES = {"red", "green"};
public static String[] getColorNames() { return COLOR_NAMES.clone(); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.