zoukankan      html  css  js  c++  java
  • Integer类小细节随笔记录

      先看一段简单的代码:

           Integer v1 = Integer.valueOf(12);
           Integer v2 = Integer.valueOf(12);
    
           Integer v3 = Integer.valueOf(129);
           Integer v4 = Integer.valueOf(129);
    
           System.out.println(v1 == v2);
           System.out.println(v3 == v4); 
    

      输出结果是啥呢?第一个是 true,第二个是false。

      为啥呢?

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

      看源代码得知,当 在默认条件下(-127到128)之间,从缓存中取值,否则重新 new 一个 Integer 对象。详细代码如下:

     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;
            }
    

      所以,我们上述的代码运行结果为 true 和 false。Integer(12) 两次都是取的缓存的值,129两次分别重新创建对象。

      不过从注释上可以了解到,可以调整jvm参数来定缓存数组的大小。

    * The cache is initialized on first usage.  The size of the cache
         * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
    

      

      再次重新运行,输出结果都为 true。因为把缓存集合的空间大小调整到了 130 + 127 ,所以 129 也从缓存中取。再试一次 取131 对比。

      

  • 相关阅读:
    ios NSString format 保留小数点 float double
    IOS中延时执行的几种方式的比较和汇总
    ioss使用xcode常用快捷键
    iphone 6plus 下app里的状态栏和界面会被放大的问题//以及设置APP闪屏页/APP图标流程
    iostbleView刷新后显示指定cell
    iOS-打包成ipa的4种方法
    iosttableViewCell右侧的箭头,圆形等
    Linux学习之CentOS(二十)------vi/vim 按键说明
    gzip
    bzip2
  • 原文地址:https://www.cnblogs.com/panzi/p/8549321.html
Copyright © 2011-2022 走看看