How to use ArrayList.addAll()?

masb picture masb · Jan 24, 2012 · Viewed 114.9k times · Source

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

Answer

bezmax picture bezmax · Jan 24, 2012

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.