下面是李sir发给我的
Integer j1 = 127;
Integer j2 = 127;
System.out.println( j1==j2); //True
Integer k1 = 128;
Integer k2 = 128;
System.out.println( k1==k2); //False
Integer w1 = -128;
Integer w2 = -128;
System.out.println( w1==w2); //True
Integer m1 = -129;
Integer m2 = -129;
System.out.println( m1==m2); //False
I've seen a lot of posts in this thread about what is happening on ==
It's simple:
When we do
Integer i = 127;
autoboxing turns this into:
Integer i = Integer.valueOf( 127 );
Go look at the implementation of Integer.valueOf(), and you'll find:
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);
}
If the int value is between -128 and 127, it will return a cached Integer value. This way we avoid creating many duplicate Integer objects for those common values. It save's on memory and improves performance.
And, of course, it does mean that Integer i = 127 will always return the same Integer instance.
再联想到以前讨论的String问题,
String a = new String("Hello World");
String b = "Hello World";
String c ="Hello World";
这里创建了几个对象,a==b么?b==c么?
这里只创建了两个新对象,一个是“Hello World”对象,另一个是与“Hello World”有相同值的对象。a b c都是对象引用。其中a==b为fasle,因为a b指向不同的对象,b==c为true,这是因为b c都指向同一个对象。因为String是一个不可变的对象,而String的直接量赋值会自动寻找以前生成了的内容相同的实例赋给引用,若以前没有内容相同的实例存在,则创建新实例。故会发生b==c。