I am stuck at this problem (sending keys to GUI) where I am converting a string to a character array then I want the characterarray as an arraylist. Essentially:
String s = "ABC";
char[] cArray = s.toCharArray();
ArrayList<Character> cList = ??
I want cList
to be a character arraylist of the form ['A', 'B', 'C']
. I don't know how to unpack it and then make an ArrayList out of it. Arrays.asList() returns a List<char[]>
which is not what I want or need.
I do know I can loop and add to a list, I am looking for something simpler (surely one exists).
Java ArrayList is an ordered collection. It maintains the insertion order of the elements. You cannot create an ArrayList of primitive types like int , char etc. You need to use boxed types like Integer , Character , Boolean etc.
We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class. Collections.
You have to loop through the array:
List<Character> cList = new ArrayList<Character>();
for(char c : cArray) {
cList.add(c);
}
Note: Arrays.asList()
works only for reference types not primitives.
Character[] chArray = {'n','a','n','d','a','n','k','a','n','a','n'};
List<Character> arrList = Arrays.asList(chArray);
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