下面是李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。