문제

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?

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top