給Integer類型賦值基本數據


給Integer類型賦值基本數據

01 運行下面代碼,num3和num2是同一個對象,num4和num5不是同一個對象

public class IntegerTest {
   public static void main(String[] args) {
      Integer num1 = new Integer(127);
      Integer num2 = 127;
      Integer num3 = 127;
      Integer num4 = 128;
      Integer num5 = 128;
      System.out.println(num1==num2);
      //結果: false
      System.out.println(num3==num2);
      //結果: true
      System.out.println(num4==num5);
      //結果: false
   }
}
 

02 通過反編譯軟件發現,直接給Integer類型賦值基本數據的底層操作使用的是valueOf()

public class IntegerTest {
  public static void main(String[] args) {
    Integer num1 = new Integer(127);
    Integer num2 = Integer.valueOf(127);
    Integer num3 = Integer.valueOf(127);
    Integer num4 = Integer.valueOf(128);
    Integer num5 = Integer.valueOf(128);
    System.out.println((num1 == num2));
    System.out.println((num3 == num2));
    System.out.println((num4 == num5));
  }
}

 

03 摘取關鍵源碼

可以看到Integer默認先創建並緩存-128~127之間數的Integer對象,當調用valueOf時,如果參數在-128~127之間則計算下標並從緩存中返回,否則創建一個新的Integer對象

public final class Integer extends Number implements Comparable<Integer> {
    
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }
}
Integer使用了享元模式,重復使用相同或像是的對象,節約系統資源

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM