5

Possible Duplicate:
New Integer vs valueOf

I read at few place that Integer.valueOf is better than new Integer(), since it allows caching of values to be done by the compiler. So when should I be using new Integer() and not Integer.valueOf(). Is there a reason/scenario where I should not be using Interger.valueOf()

Thanks

Community
  • 1
  • 1
javanerd
  • 2,802
  • 4
  • 24
  • 32

4 Answers4

5

You use new when you need distinct object identity. You use valueOf when you do not.

When you call valueOf multiple times on the same value, the JVM may, and in fact in some cases will, give you the same object over and over. When you use new, it won't. So, if you need several different 2 objects (e.g. to call wait on for different reasons), use new.

If, on the other hand, the only reason you are using Integer instead of int is to have the possibility of null, or to store in some collection, use valueOf.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
5

No, there is no scenario where new Integer() should be used. If you are distinguishing integers by their wrapper object identity then you are not likely to be doing something reasonable.

Mathias Schwarz
  • 7,099
  • 23
  • 28
1

The only reason I can think of is a scenario where you need two distinct but equal Integer objects.

System.out.println(new Integer(1)==new Integer(1)); // false
System.out.println(Integer.valueOf(1)==Integer.valueOf(1)); // true
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • one more, new Integer(xxx) is predictable and easy to fall into escape analysis, `Integer.valueOf` is a half-wit decision since it cannot be EA'd (not sure if the returned value is a new object or not). To add some more salt into the would the standard -128/+127 range can be a custom value (via -XX:AutoBoxCacheMax or -Djava.lang.Integer.IntegerCache.high) – bestsss Jul 04 '11 at 13:16
  • And why would you ever need that in practice? – Raedwald Jul 04 '11 at 13:41
  • @bestsss HotSpot (and other implementations) treat plenty of methods specially. I don't see why they shouldn't here. – Tom Hawtin - tackline Jul 04 '11 at 13:51
0

A valid reason not to use Integer.valueOf(int) would be if your project is constrained to use JDK versions before 1.5.

ewan.chalmers
  • 16,145
  • 43
  • 60