如何在 Java 中声明一个静态字符串数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16332356/
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
How to declare a static string array in Java?
提问by user1407310
I have a Java program that has two functions and a static string array. Can anybody tell me how to declare a static string array in Java?
我有一个 Java 程序,它有两个函数和一个静态字符串数组。谁能告诉我如何在 Java 中声明一个静态字符串数组?
回答by NINCOMPOOP
public static String[] stringArray = new String[size]; // give some "size"
OR
或者
public static String[] stringArray = {"String1","String2","String3"};
回答by Dave Webb
To initialise an array at construction time you can specify a list values in curly braces:
要在构造时初始化数组,您可以在花括号中指定列表值:
private static final String[] STRING_ARRAY = {"foo", "bar", "baz"};
In my example I have assumed that you won't want to change the instance of array and so have declared it final
. You still would be able to update individual entries like so:
在我的示例中,我假设您不想更改数组的实例,因此已声明它final
。您仍然可以像这样更新单个条目:
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
。
回答by yvonnezoe
public static String[] array ={"foo","bar"};