I want to fill an ArrayList
with these characters +,-,*,^ etc. How can I do this without having to add every character with arrayList.add()
?
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.
The addAll() method returns true if the collection changes as a result of elements being added into it; otherwise, it will return false .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With