Integer i=123;
Integer j=123;
System.out.println(i.equals(j));
System.out.println(i==j);//为什么是true
i=new Integer(123);
j=new Integer(123);
System.out.println(i.equals(j));
System.out.println(i==j);//为什么是false
------解决方案--------------------------------------------------------
http://www.iteye.com/topic/854960
------解决方案--------------------------------------------------------
Integer i=123; //等同于 Integer i=Integer.valueOf(123);
而new就不一样了,每new一次就有一个新地址,而==比较的就是内存地址
下面是Integer.valueOf(int i)的源码
- Java code
public static Integer valueOf(int i) { final int offset = 128; if (i >= -128 && i <= 127) { // must cache return IntegerCache.cache[i + offset]; } return new Integer(i); } private static class IntegerCache { private IntegerCache(){} static final Integer cache[] = new Integer[-(-128) + 127 + 1]; static { for(int i = 0; i < cache.length; i++) cache[i] = new Integer(i - 128); } }