问题
Possible Duplicate:
Integer wrapper objects share the same instances only within the value 127?
public class test
{
public static void main(String args[])
{
Integer a1=127;
Integer a2=127;
System.out.println(a1==a2); //output: true
Integer b1=128;
Integer b2=128;
System.out.println(b1==b2); //output: false
Long c1=127L;
Long c2=127L;
System.out.println(c1==c2); // output: true
Long d1=128L;
Long d2=128L;
System.out.println(d1==d2); //output: false
}
}
Output:
true false true false
You can use negetive values too. When you observe the outputs with the values, they behave differently. What can be the reason for such different results?
For any number the range should be -127 to +127, then ==
is true or it is false.
(All) Guys sorry it was a typo error, by mistake i put it as primitive, but it's abstract. sorry for the mistake. Now corrected...
回答1:
Integer is not a primitive, it is an object. If you used int
or long
you would only get true
.
The reason why you get this result is that Integers are cached for values between -128 and 127 so Integer i = 127
will always return the same reference. Integer j = 128
will not necessarily do so. You will then need to use equals
to test for equality of the underlying int
.
This is defined in the Java Language Specification #5.1.7.
Note that the behaviour for values outside that range [-128; 127] is undefined:
Less memory-limited implementations might, for example, cache all char and short values, as well as int and long values in the range of -32K to +32K.
回答2:
Integer isn't a primitive type but a wrapper type. See: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
回答3:
Integer
is object (wrapper class), not primitive type
It is better to do comparison like a1.intValue() == a2. intValue()
instead (or) equals()
.
回答4:
Firstly Integers are not primitives (int is). But to answer why this is happening it is because of an internal cache found in the Integer implementation:
/**
* Cache to support the object identity semantics of autoboxing for values between
* -128 and 127 (inclusive) as required by JLS.
*
* The cache is initialized on first usage. During VM initialization the
* getAndRemoveCacheProperties method may be used to get and remove any system
* properites that configure the cache size. At this time, the size of the
* cache may be controlled by the vm option -XX:AutoBoxCacheMax=<size>.
*/
So in essence when you compare two integers that have been cached you are comparing the same object to itself, so the == returns true, however when you're comparing Integers above 127 or below -127 (non cached Integers) you are comparing two different Integer instances.
If you use the equals or compareTo methods you'll get what you expected to see.
来源:https://stackoverflow.com/questions/11955958/with-abstract-datatypes-different-results-for-the-same-kind-of-conditions