Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add multiple items to already initialized arraylist in java

I'm googling it and can't seem to find the syntax. My arraylist might be populated differently based on a user setting, so I've initialized it

ArrayList<Integer> arList = new ArrayList<Integer>(); 

And now I'd like to add hundred of integers without doing it one by one with arList.add(55);

like image 765
batoutofhell Avatar asked Mar 05 '13 00:03

batoutofhell


People also ask

How do you add multiple elements to an ArrayList at once?

addAll() We can add all items from another collection to an ArrayList using addAll() . List<String> lst = new ArrayList<>(); lst.

Can you add items to an ArrayList after it has been declared?

You cannot add or remove elements into this list but when you create an ArrayList like new ArrayList(Arrays. asList()), you get a regular ArrayList object, which allows you to add, remove and set values.


1 Answers

If you have another list that contains all the items you would like to add you can do arList.addAll(otherList). Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll() method, with something like

Integer[] otherList = new Integer[] {1, 2, 3, 4, 5}; arList.addAll(Arrays.asList(otherList)); 

or, if you don't want to create that unnecessary array:

arList.addAll(Arrays.asList(1, 2, 3, 4, 5)); 

Otherwise you will have to have some sort of loop that adds the values to the list individually.

like image 61
scaevity Avatar answered Sep 23 '22 17:09

scaevity