11

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

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm pretty sure that it will autobox primitives. Unless you're very concerned about performance I don't see a reason not to use it.
@Aurand, not really. Arrays.asList(new char[]{'a','b', 'c'}) actually returns a List with only one element: an array with 'a', 'b' and 'c', not a List with three items as one would maybe expect.
4

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)

1 Comment

While @Bhesh Gurung had a helpful answer I was looking for the more direct method, will accept this as my answer (and get to install Google Guava).
3
Character[] chArray = {'n','a','n','d','a','n','k','a','n','a','n'};

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.