Int
Int是Java八種基本資料型別之一,一般大小為4位元組32位,取值范圍為2-31—231,兩個Int型別變數用“==”比較的是值的大小,
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
int a = 100;
int b = 100;
System.out.println(a == b);//true
}
}
Integer和Integer.valueOf()
將Int值賦給Integer變數,系統會自動將這個Int值封裝成一個Integer物件,
比如:Integer a = 100;實際上的操作是:Integer a = Integer.valueOf(100);
以下是valueOf()的原始碼

注意:這里Integer.valueOf(),當Int值的范圍在-128-127之間時,會通過一個IntegerCache快取來創建Integer物件;當Int值不在該范圍時,直接呼叫new Integer()來創建物件,因此會出現以下的情況
(1)Integer a = 100; Integer b = 100; a==b結果為true,因為這兩個Integer變數參考的是快取中的同一個Integer物件 ;
(2)Integer c = 200; Integer d = 200; a==b結果為false,因為a和b是通過new Integer() 創建的兩個不同物件,
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
System.out.println(a == b);//true
System.out.println(c == d);//false
}
}
new Integer()
new Integer()每次都會創建新的物件,==比較的是兩個物件的記憶體地址
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
Integer a = new Integer(100);
Integer b = new Integer(100);
System.out.println(a == b);//false
}
}
三者之間的比較
(1)不管是new創建的Integer物件,還是通過直接賦值Int值創建的Integer物件,它們與Int型別變數通過“==”進行比較時都會自動拆箱變成Int型別,所以Integer物件和Int變數比較的是內容大小,
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
int a = 100;
Integer b = 100;//等價于b=Integer.valueOf(100);
Integer c = new Integer(100);
System.out.println(a == b);//true
System.out.println(a == c);//true
}
}
(2)new創建的Integer物件和直接賦Int值創建的Integer物件使用==比較的是它們的記憶體地址,
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
Integer b = 100;//等價于b=Integer.valueOf(100);
Integer c = new Integer(100);
System.out.println(b == c);//false
}
}
(3)賦Int值創建的Integer物件比較:
當Int值在-128-127之間時,兩個Integer變數參考的是IntegerCache中的同一個物件,記憶體地址相同,因此==的結果為true;
當Int值不在以上范圍時,兩個Integer物件都是通過new創建的,記憶體地址不同,因此==的結果為false
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
Integer a = 100;
Integer b = 100;
Integer c = 200;
Integer d = 200;
Integer f = new Integer(100);
System.out.println(a == b);//true
System.out.println(c == d);//false
System.out.println(a == f);//false
}
}
一個金典面試題
package com.company.algorithm;
public class Main {
public static void main(String[] args) {
Integer a = 49;
int b = 49;
Integer c = Integer.valueOf(49);
Integer d = new Integer(49);
System.out.println(a == b);//true
System.out.println(a == c);//true
System.out.println(b == c);//true
System.out.println(c == d);//false
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/352200.html
標籤:java
下一篇:Java網路編程基礎
