36

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

Egor
  • 39,695
  • 10
  • 113
  • 130
masb
  • 2,813
  • 3
  • 20
  • 20

6 Answers6

82

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.

bezmax
  • 25,562
  • 10
  • 53
  • 84
7

Assuming you have an ArrayList that contains characters, you could do this:

List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • 4
    `Collections.addAll` is a better way to go, as it simply iterates through given items adding all of them to the list, while with `Arrays.asList` you would create a temporary `List` object to achieve the same result. – bezmax Jan 24 '12 at 11:01
3

You can use Google guava as such:

ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');
leokash
  • 200
  • 1
  • 6
1

You can use the asList method with varargs to do this in one line:

java.util.Arrays.asList('+', '-', '*', '^');

If the list does not need to be modified further then this would already be enough. Otherwise you can pass it to the ArrayList constructor to create a mutable list:

new ArrayList(Arrays.asList('+', '-', '*', '^'));
Jörn Horstmann
  • 33,639
  • 11
  • 75
  • 118
0

May be this helps

List<String> l = Arrays.asList("+","-");
baba.kabira
  • 3,111
  • 2
  • 26
  • 37
0

Use Arrays class in Java which will return you an ArrayList :

final List<String> characters = Arrays.asList("+","-");

You will need a bit more work if you need a List<Character>.

vanadium
  • 51
  • 1
  • Actually, for it to be a `List` you simply change `"` to `'` and `List` to `List`. Generics will handle the rest. – bezmax Jan 24 '12 at 10:59