问题
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