Why would one want to use the public constructors on Boolean and similar immutable classes?
Posted
by Robert J. Walker
on Stack Overflow
See other posts from Stack Overflow
or by Robert J. Walker
Published on 2010-04-08T16:56:11Z
Indexed on
2010/04/08
17:03 UTC
Read the original article
Hit count: 190
(For the purposes of this question, let us assume that one is intentionally not using auto(un)boxing, either because one is writing pre-Java 1.5 code, or because one feels that autounboxing makes it too easy to create NullPointerException
s.)
Take Boolean
, for example. The documentation for the Boolean(boolean)
constructor says:
Note: It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory
valueOf(boolean)
is generally a better choice. It is likely to yield significantly better space and time performance.
My question is, why would you ever want to get a new instance in the first place? It seems like things would be simpler if constructors like that were private. For example, if they were, you could write this with no danger (even if myBoolean
were null
):
if (myBoolean == Boolean.TRUE)
It'd be safe because all true Booleans
would be references to Boolean.TRUE
and all false Booleans
would be references to Boolean.FALSE
. But because the constructors are public, someone may have used them, which means that you have to write this instead:
if (Boolean.TRUE.equals(myBoolean))
But where it really gets bad is when you want to check two Booleans
for equality. Something like this:
if (myBooleanA == myBooleanB)
...becomes this:
if (
(myBooleanA == null && myBooleanB == null) ||
(myBooleanA == null && myBooleanA.equals(myBooleanB))
)
I can't think of any reason to have separate instances of these objects which is more compelling than not having to do the nonsense above. What say you?
© Stack Overflow or respective owner