arynaq
arynaq

Reputation: 6870

Converting array of characters to arraylist of characters

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

Upvotes: 11

Views: 25575

Answers (3)

Kishore
Kishore

Reputation: 55

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

List<Character> arrList = Arrays.asList(chArray);

Upvotes: 3

JohnnyO
JohnnyO

Reputation: 3068

To my knowledge, this does not exist in the core JDK, but the functionality is provided by several common libraries.

For example, Apache Commons Lang has a method with the following signature in ArrayUtils:

Character [] toObject(char [] input)

Similarly, the Google Guava library has a even more direct method in the Chars class:

public static List<Character> asList(char... backingArray)

Upvotes: 4

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

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.

Upvotes: 15

Related Questions