0

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?

5
  • 2
    new String <-- error here. And message.toArray() will only accept an array as an argument, which stringMessage is not. Commented Mar 19, 2014 at 20:13
  • Even if toArray accepted String as argument (It doesn't), it still returns an array Commented Mar 19, 2014 at 20:14
  • possible duplicate of Converting ArrayList of Characters to a String? Commented Mar 19, 2014 at 20:15
  • First error can be resolved by simply writing String stringMessage;. But what are you really trying to do? The third line doesn't make sense. Commented Mar 19, 2014 at 20:25
  • To clearify: I'm using ArrayList as it has some advantages when handeling the data during the program, but for functions that can only handle the String object I need to do this conversion. Thank you all for the quick replies, fge's code solved my problem. Commented Mar 19, 2014 at 20:48

1 Answer 1

0

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

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

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.