zoukankan      html  css  js  c++  java
  • 有关于Integer的一些小问题

    先看一小段源码:

        Integer a1=100;
        Integer a2=100;
        Integer b1=new Integer(100);
        Integer b2=new Integer(100);
        Integer c1=128;
        Integer c2=128;
        System.out.println(a1==a2);
        System.out.println(b1==b2);
        System.out.println(c1==c2);

    输出结果:true  false,false;

      首先b1==b2这个肯定是false,通过关键字new出来的地址存储在堆区并且地址是不同的,所以引用也不会相同

      关键是a和c都是直接赋值,为什么结果不一样呢?

      这是因为Integer作为int的包装类,它能对一定范围类的数据有缓存.(通过查看Integer类的源码)

      

    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 =
                    sun.misc.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() {}
        }

    这个具体的范围可知为:-128-127

        然后直接赋值的时候,会内部调用Integer的valueof(int)的方法

        

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

        valueof(int)方法,若数值在-128-127之间,直接从缓存cache中读取,若是不在,直接通过new操作符创建

        

      

  • 相关阅读:
    flex space-between最后一行对齐问题的解决方案
    如何在父级下访问v-slot的值——vuejs
    flex下省略号的问题解决
    Typescript使用字符串联合类型代替枚举类型
    flex三个对齐属性的记忆方式
    JS中的slice()和splice()的区别以及记忆方式
    JS中的call,apply和bind及记忆方式
    Vue 还是 React 还是 Angular ?
    利用ES6的Promise.all实现至少请求多长时间
    .net core <environment> 不起作用
  • 原文地址:https://www.cnblogs.com/goxcheer/p/7866841.html
Copyright © 2011-2022 走看看