zoukankan      html  css  js  c++  java
  • 关于Integer 和Double包装类创建对象时的底层解析

    public void method1() {
        Integer i = new Integer(1);
        Integer j = new Integer(1);
        System.out.println(i == j);
        Integer m = 1;
        Integer n = 1;
        System.out.println(m == n);//True
        Integer x = 128;
        Integer y = 128;
        System.out.println(x == y);//False
    }

    如题,当数值大于等于128时,创建的俩个对象地址就不一样了,这个原因还得看Integer的源码

    1 public static Integer valueOf(int i) {
    2     if (i >= IntegerCache.low && i <= IntegerCache.high)//-128~127
    3         return IntegerCache.cache[i + (-IntegerCache.low)];
    4     return new Integer(i);
    5 }

    这个IntegerCache 数组是包装类自己创建的缓存数组,里面存放着【-128,127】的整数,当数值在这个范围时,会从这个数组中直接取值,当数值不在这个范围时,就会新建对象,所以地址就会不一样

    -------------------------------------------------

    那么Double类型的呢

        public static void main(String[] args) {
            double a = 2.0;
            double b = 2.0;
            Double c = 2.0;
            Double d = 2.0;
            System.out.println(a == b);//true
            System.out.println(c == d);//false
            System.out.println(a == d);//true
        }

    进源码

    public static Double valueOf (double d){
                   return  new  Double (d)   ;
        
    }    

    显然,Double没有Integer花里胡哨,只有调用就新建一个对象

  • 相关阅读:
    B. Spreadsheets
    Frequent values 倍增/线段树离散化
    E. Tree Painting 二次扫描换根法
    1405 树的距离之和 二次扫描换根法
    D. Subarray Sorting
    K
    Max answer(单调栈,rmq)
    POJ2823 (单调队列)
    POJ2559(单调栈入门)
    Principles and strategies for mathematics study
  • 原文地址:https://www.cnblogs.com/yangxusun9/p/12178093.html
Copyright © 2011-2022 走看看