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.
Assuming you have an ArrayList
that contains characters, you could do this:
List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));
-
4
Collections.addAll
is a better way to go, as it simply iterates through given items adding all of them to the list, while withArrays.asList
you would create a temporaryList
object to achieve the same result.– bezmaxJan 24, 2012 at 11:01
You can use Google guava as such:
ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');
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('+', '-', '*', '^'));
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>
.
-
Actually, for it to be a
List<Character>
you simply change"
to'
andList<String>
toList<Character>
. Generics will handle the rest.– bezmaxJan 24, 2012 at 10:59