How to use ArrayList.addAll()?

 ̄綄美尐妖づ 提交于 2019-12-20 16:13:35

问题


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


回答1:


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.




回答2:


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

List<Character> list = new ArrayList<Character>();
list.addAll(Arrays.asList('+', '-', '*', '^'));



回答3:


You can use Google guava as such:

ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');



回答4:


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



回答5:


May be this helps

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



回答6:


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>.



来源:https://stackoverflow.com/questions/8985432/how-to-use-arraylist-addall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!