Sunday, October 21, 2007

new Boolean()

Java, for some strange reason had constructors for the Boolean object:
Boolean(boolean b) and Boolean(String s).
I could not think of any situation where this is useful (In fact the javadoc for the first form mentions it, but not the second). Consider the following:

Boolean b = new Boolean("true");
Boolean b1 = new Boolean(true);
Boolean b2 = Boolean.TRUE;

Now we have three object references, which are conceptually the same but not equal. Here, b == b1, b == b2 and b1 == b2 all result in false.

Looks like Auto boxing in 1.5 at least takes care of this, So if we have

Boolean b1 = true;
Boolean b2 = Boolean.TRUE;

b1 == b2 is indeed true. (Boolean.valueOf() methods had no problem anyway)

btw, a Boolean can be thought of as an example of a Flyweight.

No comments: