一次将多个项目添加到 Java 中的 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43457079/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:54:47  来源:igfitidea点击:

Adding multiple items at once to ArrayList in Java

javaarraylistaddelements

提问by Lealo

How can I add multiple items at once to an ArrayList? ArrayList<Integer> integerArrayList = new ArrayList();Instead of: integerArrayList.add(1)integerArrayList.add(2)integerArrayList.add(3)integerArrayList.add(4)...

如何一次向 ArrayList 添加多个项目? ArrayList<Integer> integerArrayList = new ArrayList();而不是: integerArrayList.add(1)integerArrayList.add(2)integerArrayList.add(3)integerArrayList.add(4)...

I would like to: integerArrayList.add(3, 1, 4, 2);So that I wont have to type so much. Is there a better way to do this?

我想:integerArrayList.add(3, 1, 4, 2);这样我就不用打那么多字了。有一个更好的方法吗?

采纳答案by Zircon

Use Collections.addAll:

使用Collections.addAll

Collections.addAll(integerArrayList, 1, 2, 3, 4);

回答by kar

Is your List fixed? If yes the following should work.

你的清单是固定的吗?如果是,以下应该有效。

List<Integer> integerArrayList = Arrays.asList(1, 2, 3);

回答by Jacob G.

If the Listwon't need to be added/removed to/from after it's initialized, then use the following:

如果在List初始化后不需要添加/删除它,则使用以下命令:

List<Integer> integerArrayList = Arrays.asList(1, 2, 3, 4);

Otherwise, you should use the following:

否则,您应该使用以下内容:

List<Integer> integerArrayList = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

回答by Teto

Would something like this work for you.

像这样的东西对你有用吗?

    Integer[] array = {1,2,3,4};
    ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));

Or you could use a loop to fill the list.

或者您可以使用循环来填充列表。

int i;
for(i = 0; i < 1000; i++){
   list.add(i);
}