Why do the Integer.valueOf(...) comparisons in this example return different values?
From the answer to a ques开发者_如何学Gotion 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?
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.
See Integer.valueOf realization: http://docjar.com/html/api/java/lang/Integer.java.html (850s line)
Integer.valueOf caches values, specifically -128 to 127.
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>
精彩评论