Bitten by the specialness of Java arrays
February 18, 2009
Suppose you have some text in Java that you want to manipulate. There are classes like StringBuffer for doing so, but let’s imagine that you choose to use a char array for some special reason.
Now suppose that several pages of code later, perhaps in a different piece of code entirely, you decide to use the value of the variable. At that point, you’ve forgetten that you didn’t use a StringBuffer, so you do the usual thing and call the toString() method.
Here’s some code to simulate what happens:
char []s = "Results of some computation".toCharArray();
// Lots of code later
System.out.println(s.toString());
When I compile and run the above, it outputs [C@1bc4459, which isn’t at all what you might hope.
There are two obvious questions which occur to me. The first is to wonder if this behavior of Java is deliberate. Is it considered useful in some way, or just an accident of implementation?
The second and more important question is: How can I detect such errors before code goes into production? Eclipse doesn’t catch it, and nor does PMD.
Filed under: Java | Comments (4)
Ah, the reference type that is not an object. Doncha just love arrays?
All arrays get their methods from Object (except for “clone”). Is this intended, or merely accidental? Hard to say, probably a bit of both (they intended to do something simple to implement, for example).
I like your second question, but I have no idea how to detect such errors. There’s probably some schools of Java programming that would ban all use of «char []» (and surely that’s easy to check for).
I wouldn’t use char[] myself, but for some reason Sun introduced an API change in Swing that makes password fields return char[] instead of the deprecated String values they used to return.
Ooh. I hope it’s a fresh one. Bloch item 12.
Allegedly it’s to make it harder to suck passwords out of memory.
Riiight.