Reputation: 638
From the answer to a question about primitive types and autoboxing in java:
for biziclop:
class biziclop {
public static void main(String[] args) { System.out.println(new Integer(5) == new Integer(5)); System.out.println(new Integer(500) == new Integer(500)); System.out.println(Integer.valueOf(5) == Integer.valueOf(5)); System.out.println(Integer.valueOf(500) == Integer.valueOf(500)); }
}
Results in:
C:\Documents and Settings\glow\My Documents>java biziclop false false true false C:\Documents and Settings\glow\My Documents>
Why is that?
Upvotes: 2
Views: 804
Reputation: 75356
Integer.valueof caches objects for values around zero as required by the Java Language Specification.
Inspired by ilya's answer see the latest, actual source for Integer.valueOf() in the upcoming JDK7, lines 638-643.
Upvotes: 3
Reputation: 4564
You should use the equal method not the == operator. == test if two objects are equal but you create different objects with same value and need the equal()
method to compare the object's values.
Update:
Reason for different behavior of Integer.valouOf(5)
and Integer.valouOf(500)
is indeed that Integer implementation uses a static valueOfCache of size -128..127.
As of Java 7 this is configurable with the command-line argument -XX:AutoBoxCacheMax=<size>
Upvotes: 1
Reputation: 3078
See Integer.valueOf realization: http://docjar.com/html/api/java/lang/Integer.java.html (850s line)
Upvotes: 3