4

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?

Lealo
  • 331
  • 1
  • 3
  • 11

4 Answers4

14

Use Collections.addAll:

Collections.addAll(integerArrayList, 1, 2, 3, 4);
Zircon
  • 4,677
  • 15
  • 32
7

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

List<Integer> integerArrayList = Arrays.asList(1, 2, 3);
kar
  • 4,791
  • 12
  • 49
  • 74
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));
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
2

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);
}
Teto
  • 475
  • 2
  • 10