System.out.println("<-128~127以内的Integer值,Integer x = value;的方式赋值!>");Integer i = 127;Integer j = 127;System.out.println("i=" + i + ",j =" + j);System.out.println("i == j:" + (i == j) + "<--比较-->i.equals(j):"+ i.equals(j));System.out.println("<-128~127以外的Integer值,Integer x = value;的方式赋值!>");Integer m = 128;Integer n = 128;System.out.println("m=" + m + ",n =" + n);System.out.println("m == n:" + (m == n) + "<--比较-->m.equals(n):"+ m.equals(n));System.out.println(); System.out.println("<任意Integer值,Integer x = new Integer(value);的方式赋值!>");Integer x = new Integer(299);Integer y = new Integer(299);System.out.println("x=" + x + ",y =" + y);System.out.println("x == y:" + (x == y) + "<--比较-->x.equals(y):"+ x.equals(y));
输出结果为:
代码语言:javascript
复制
<-128~127以内的Integer值,Integer x = value;的方式赋值!>i=127,j =127i == j:true<--比较-->i.equals(j):true<-128~127以外的Integer值,Integer x = value;的方式赋值!>m=128,n =128m == n:false<--比较-->m.equals(n):true
<任意Integer值,Integer x = new Integer(value);的方式赋值!>x=299,y =299x == y:false<--比较-->x.equals(y):true
通过以上代码及输出结果,想必大家已经看出其中奥秘!先总结如下:
1、以上代码第一段和第二段旨在说明:在-128~127的Integer值并且以Integer x = value;的方式赋值的Integer值在进行==和equals比较时,都会返回true,因为Java里面对处在在-128~127之间的Integer值,用的是原生数据类型int,会在内存里供重用,也就是说这之间的Integer值进行==比较时只是进行int原生数据类型的数值比较,而超出-128~127的范围,进行==比较时是进行地址及数值比较。
2、第三段旨在说明:==和equals的区别,==是进行地址及值比较,无法对==操作符进行重载,而对于equals方法,Integer里面的equals方法重写了Object的equals方法,查看Integer源码可以看出equals方法进行的是数值比较。
续详解:
首先看一段代码(使用JDK 5),如下:
public class Hello
{
public static void main(String[] args)
{
int a = 1000, b = 1000;
System.out.println(a == b);
Integer c = 1000, d = 1000;
System.out.println(c == d);
Integer e = 100, f = 100;
System.out.println(e == f);
}
}
输出结果:
true
false
true
The Java Language Specification, 3rd Edition 写道: view plaincopy
为了节省内存,对于下列包装对象的两个实例,当它们的基本值相同时,他们总是==:
Boolean
Byte
Character, \u0000 - \u007f(7f是十进制的127)
Integer, -128 — 127
查看jdk源码,如下:
[java] view plaincopy
/**
* 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>.
*/
// value of java.lang.Integer.IntegerCache.high property (obtained during VM init)
If the value p being boxed is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.