2

This is baffling me. I am grabbing a String and converting it to a Char array but the resulting characters are not the same as the original String. What gives? I've tried it one character at a time as well as trying toCharArray(). Same results.

Output:

07-21 09:58:27.700: V/meh(22907): Loaded String = [C@42126d88

07-21 09:58:27.700: V/meh(22907): Convert to Char = [C@41693070

String temp = prefManager_.getString("PrevGameState", "");
Log.v("meh", "Loaded String = " + temp);

pieceStates_ = temp.toCharArray();
Log.v("meh", "Convert to Char = " + pieceStates_.toString());

2 Answers 2

4

The value it outputs is not a string indeed, it's a pointer in memory. Probably you are not overriding the toString() method or there is something wrong.

The fact that the two pointers are not the same doesn't mean that the two strings are not equal (which should be compared with .equals(..) and not in any different way).

To be more precise, if pieceStates_.toString() prints [C@41693070 then the toString is not overridden and Java doesn't know how to print it. Same thing applies to the other variable. Then an array type in Java is not printable by default, you should use Arrays.toString(..) to actually see its content.

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

5 Comments

07-21 10:41:17.997: V/meh(23890): .equals = false Log.v("meh", ".equals = " + pieceStates_.toString().equals(temp));
Of course they are not equal: in Java a char[] is NOT equal to a String containing the same characters and I don't see why it should. You are comparing radical different objects.
Log.v("meh", ".equals = " + pieceStates_.toString().equals(temp));
I converted to string before using the .equals function as you recommended. It is false. So no, I am not comparing char [] to String.
As I stated: you are converting a char[] array with an implicit conversion which is NOT meant to generate the string defined by the char array but a printable representation of the array (and of arrays in general). toString is NOT meant to be used on a char[].
2

Use :

System.out.println("Convert to Char = " + String.valueOf(pieceStates_) );

String.valueOf(Character_Array)

Above method converts it back to String object.

3 Comments

Apparently String.valueOf is the way to go and charArray.toString is useless. This solved my problem. Thanks!
it's not useless, you were just trying to use for something that it doesn't work for =).
What does it do if not convert the character array to a string?

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.