Java 将多个项目添加到数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24550801/
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
Add multiple items to an array
提问by jknudsen99
So lets say I want to make an array of nine country names. I have the code to create the array:
所以假设我想制作一个包含九个国家/地区名称的数组。我有创建数组的代码:
String[] countryName = new String[9];
Lets say I wanted to add nine unique country names to this array. I could do something like this:
假设我想向这个数组添加九个唯一的国家名称。我可以做这样的事情:
countryName[0] = "Mexico";
countryName[1] = "United States";
and so on. But is there a way I could add all of the names at once? Maybe something like an add() statement?
等等。但是有没有一种方法可以一次添加所有名称?也许类似于 add() 语句?
采纳答案by Michel Foucault
you can initialize the array with:
您可以使用以下方法初始化数组:
String[] countryName = new String[]{"Mexico", "Italy", "Spain"};
回答by CoderCroc
Enlist all contries in String
and use split
登记所有国家String
并使用split
String str="Country1,Country2,Country3";
String array[]=str.split(",");//You even don't need to initialize array
Use delimeter carefully to avoid extra spaces.
小心使用分隔符以避免多余的空格。
NOTE:
As this is one of the ways to add values to array but still I suggest you to go for Michel Foucault
's answer as split
will have more overhead than direct initialization.
注意:因为这是向数组添加值的方法之一,但我仍然建议您选择Michel Foucault
's answer ,因为它split
比直接初始化有更多的开销。
回答by Ilya
You can write simple utility method using varargs
您可以使用编写简单的实用方法 varargs
static void addAll(String[] arr, String ... elements)
{
if (elements != null)
{
System.arraycopy(elements, 0, arr, 0, elements.length);
}
}
Usage
用法
addAll(countryName, "Mexico", "US", "Ukraine");
回答by DannyFeliz
Use an ArrayList this has the Add method.
使用具有 Add 方法的 ArrayList。
ArrayList<String> countryName = new ArrayList<String>();
countryName.add("Mexico");
countryName.add("United States");
countryName.add("Dominican Republic");
countryName.add("...");