Thursday, May 3, 2012

new vs. valueOf() in Java primitive wrappers

Did you ever take a close look at the Javadoc which is written at, for example, Integer.valueOf()?

No? Ok, I'll tell you ;)

It says you should prefer using the valueOf() method instead of using Integer's constructor. You'll find the same annotation at all the other wrapper classes for the primitive types in Java. (in Double, the Javadoc says the same, but double doesn't have a cache, weird...)

The reason is that Java will cache some values, so the VM won't create a lot of new objects.
I cannot imagine a certain case, when I explicitly need a new Integer or something similar (maybe in a JUnit-Test). A friend of mine mentioned when it's the key of a WeakHashMap.

So the next time you want to type new Integer(...), consider using Integer.valueOf(...) ;)

0 comments:

Post a Comment

 

Copyright @ 2013 Wrong tracks of a developer.

Designed by Templateiy