Adding multiple items at once to ArrayList in Java [duplicate]

北城余情 提交于 2019-12-21 23:28:38

问题


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) ...

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?


回答1:


Use Collections.addAll:

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



回答2:


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

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



回答3:


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

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));



回答4:


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);
}


来源:https://stackoverflow.com/questions/43457079/adding-multiple-items-at-once-to-arraylist-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!