I want to fill an ArrayList
with these characters +,-,*,^ etc. How can I do this without having to add every character with arrayList.add()
?
6 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.

- 25,562
- 10
- 53
- 84
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));

- 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
You can use Google guava as such:
ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');

- 200
- 1
- 6
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('+', '-', '*', '^'));

- 33,639
- 11
- 75
- 118
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>
.

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