Friday, June 23, 2006

Java 4s

Try this in java:

(4 == 4)
(new Integer(4) == new Integer(4))

well the first one is true, the second one is false. Why do I need 2 instances of the number (integer) 4 in java I don't know. I couldn't find any example (excuse). After all 4 is immutable, I cannot change it's state, I cannot make a 5 out of it.

I could say that in Smalltalk, or ruby, where everything is an object, yada, yada.... But Sun owns Java,
they own the Integer class, so when I call the constructor I should always get the same instance.

and we have the same symptoms (changed behaviour) with booleans:

(false == false)
(new Boolean(false) == new Boolean(false))

WTF !? I can have a million false objects in java. And for What? To be garbage collected, from autoboxing/unboxing? How hard is it to create a pool inside the Boolean class and to return always the FALSE object  for Boolean(false) ?

Finally, there is another guy who feels my pain: "Java's new Considered Harmful . The problem stems from memory allocation and polymorphsim". Well actually he feels more pain, but that's his problem :D

No comments: