基本資料型別和包裝類的關係(以int和Integer為例)
阿新 • • 發佈:2018-12-11
public void test(){ int a=10; Integer b=new Integer(10); Integer d= Integer.valueOf(10); Integer e= Integer.valueOf(10); Integer c=10; Integer f=10; System.out.println(a==b);//b自動拆箱int。基本型別比較值 true System.out.println(a==c);//將右邊的1自動裝箱,然後將c自動拆箱比較值true System.out.println(c==b);//b,c都是引用型別,比較地址。指向不同物件 false System.out.println(c.equals(b));//都是引用資料型別,重寫equals。比較的是值true System.out.println(c.equals(a));//首先將a自動裝箱。相同的物件相同的值。true System.out.println(c.equals(new Float(10)));//物件不同值相同。false System.out.println(c.equals(new Integer(1)));//物件相同但是值不同false System.out.println(a==d);//含有基本資料型別時,將包裝類自動拆箱比較值true System.out.println(d.equals(e));//同類型同值true System.out.println(d==e);//比較地址。-128<value<127是建立了相同物件。true System.out.println(d==f);//true }
主要涉及的就是自動裝,拆箱。以及Integer重寫的equals方法和自己帶的valueof方法。
==:對於基本的資料型別(8種,String不是),比較的是值
對於引用資料型別(除基本型別以外),比較的是地址。也即兩個引用是否指向同一個物件。
equals:對於重寫了object下的equals方法來說,大部分比較的是值(若是自己定義的類沒有重寫,則比較的仍是地址)。注意比較得是值的有一個前提就是兩個比較的是同一型別。這可以在重寫的equals原始碼中看見(Integer)
原始碼: public boolean equals(Object obj) {
return value == ((Integer)obj).intValue();
}
return false;
}
valueof:對於該方法需要注意的是它在[-128,127]內建立是同一個物件,這是JVM為了便於提高效率決定的。在原始碼中可以看見(Integer為例)
原始碼:
public static Integer valueOf(int i) {
final int offset = 128;if (i >= -128 && i <= 127) { // must cache
}
return new Integer(i);
}。