1. 程式人生 > 程式設計 >簡單瞭解java中int和Integer的區別

簡單瞭解java中int和Integer的區別

這篇文章主要介紹了簡單瞭解java中int和Integer的區別,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

1、Integer是int的包裝類,int則是java的一種基本資料型別

2、Integer變數必須例項化(new 一下是最常見的例項化)後才能使用,而int變數不需要

3、Integer實際是物件的引用,new Integer(),實際上是生成一個指標指向此物件;而int則是直接儲存資料值

4、Integer的預設值是null,int的預設值是0

注意

Integer物件會佔用更多的記憶體。Integer是一個物件,需要儲存物件的元資料。但是int是一個原始型別的資料,所以佔用的空間更少

關於Integer和int的比較

1. 兩個new例項化出來的Integer變數比較,結果為false.

/**
 * @author tracydzf
 *比較兩個new出來的Integer
 *
 */
public class Test {

  public static void main(String[] args) {
    Integer a = new Integer(100);
    Integer b = new Integer(100);
    System.out.println(a==b);
    //輸出false    
  }
}

當new一個Integer時,實際上是生成一個指標,指向此物件,兩次new Integer生成的是兩個物件,物件儲存在堆當中,其記憶體地址不同,所以兩個new出來的Integer變數不等。

2.int 和Integer在進行比較的時候,Integer會進行拆箱,轉為int值與int進行比較

/**
 * @author tracydzf
 *int 和 Integer的比較
 *
 */

public class Test {

  public static void main(String[] args) {
    Integer a = new Integer(100);
    int b = 100;
    System.out.print(a == b); //true  
  }
}

3.非new生成的Integer變數和new Integer()生成的變數比較時,結果為false。(因為非new生成的Integer變數指向的是java常量池中的物件,而new Integer()生成的變數指向堆中新建的物件,兩者在記憶體中的地址不同)

/**
 * @author tracydzf
 * Integer 和 new Integer的比較
 *
 */
public class Test {

  public static void main(String[] args) {
    Integer a = new Integer(100);
    Integer b = 100;
    System.out.print(a == b); //false  
  }
}

4.對於兩個非new生成的Integer物件,進行比較時.

注意:

① java在編譯Integer i = 100 ;時,會翻譯成為Integer i = Integer.valueOf(100),java API中對Integer型別的valueOf的定義如下:

public static Integer valueOf(int i){
  assert IntegerCache.high >= 127;
  if (i >= IntegerCache.low && i <= IntegerCache.high){
    return IntegerCache.cache[i + (-IntegerCache.low)];
  }
  return new Integer(i);
}

② 當自動裝箱後生成的Integer的物件,其值 -128<= x <= 127 時,這個物件會直接取快取IntegerCache中的對應的物件,生成的當然也是個物件。

我們來看看例子

這裡a跟b都是128,不會再IntegerCache取快取物件,所以是false.

/**
 * @author tracydzf
 * Integer 和 Integer的比較
 *
 */
public class Test {

  public static void main(String[] args) {
    Integer a = 128;
    Integer b = 128;
    System.out.print(a == b); //false  
  }
}

a,b都是127,數值相等,且滿足在IntegerCache取快取的條件,所以物件相等.

/**
 * @author tracydzf
 * Integer 和 Integer的比較
 *
 */
public class Test {

  public static void main(String[] args) {
    Integer a = 127;
    Integer b = 127;
    System.out.print(a == b); //true
  }
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。