Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting array of characters to arraylist of characters

Tags:

java

arrays

list

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

like image 643
arynaq Avatar asked Feb 25 '13 21:02

arynaq


People also ask

Can you make an ArrayList of characters?

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.

Can you convert array to ArrayList?

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.


2 Answers

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.

like image 74
Bhesh Gurung Avatar answered Sep 17 '22 21:09

Bhesh Gurung


Character[] chArray = {'n','a','n','d','a','n','k','a','n','a','n'};

List<Character> arrList = Arrays.asList(chArray);
like image 45
Kishore Avatar answered Sep 19 '22 21:09

Kishore