Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ArrayList.addAll()?

I want to fill an ArrayList with these characters +,-,*,^ etc. How can I do this without having to add every character with arrayList.add()?

like image 1000
masb Avatar asked Jan 24 '12 10:01

masb


People also ask

What does ArrayList addAll do?

addAll. Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

What does addAll () do in Java?

The addAll() method returns true if the collection changes as a result of elements being added into it; otherwise, it will return false .

How do you use add all in ArrayList?

Example 3: Inserting Elements from Set to ArrayListaddAll(set); Here, we have used the addAll() method to add all the elements of the hashset to the arraylist. The optional index parameter is not present in the method. Hence, all elements are added at the end of the arraylist.


Video Answer


1 Answers

Collections.addAll is what you want.

Collections.addAll(myArrayList, '+', '-', '*', '^'); 

Another option is to pass the list into the constructor using Arrays.asList like this:

List<Character> myArrayList = new ArrayList<Character>(Arrays.asList('+', '-', '*', '^')); 

If, however, you are good with the arrayList being fixed-length, you can go with the creation as simple as list = Arrays.asList(...). Arrays.asList specification states that it returns a fixed-length list which acts as a bridge to the passed array, which could be not what you need.

like image 125
bezmax Avatar answered Sep 27 '22 17:09

bezmax