Search code examples
javaarraylistcastingprocessingtoarray

.toArray from ArrayList to Array convertion, data type confusion


I have confused myself with typecasting with this problem.

I have an ArrayList of chars that I want to convert into a String—an array of chars. So it goes something like this:

ArrayList<Character> message = new ArrayList<Character>();
String stringMessage = new String;
stringMessage = message.toArray(stringMessage);

Now the error that is given is:

"Syntax error, maybe a missing semicolon?"

which isn't very helpful.

Is there something wrong with how I cast this? Is it not possible to convert an ArrayList of characters into a String?


Solution

  • You can do this:

    final CharBuffer buf = CharBuffer.allocate(message.size());
    for (final Character c: message)
        buf.put(c.charValue());
    stringMessage = new String(buf.array());
    

    You cannot use .toArray() directly since it would return a Character[], not a char[], and there is no String constructor accepting a Character[] as an argument...