zoukankan      html  css  js  c++  java
  • Integer代码分析

    我们都知道Integer是int的封装类,提供了一些类型转换等工具方法,有一个-128-127的缓存,而且是final的。
    -----------------------------
    干货:
    Integer是final 的,因此对Integer的操作返回的都是另一个新对象,而不是修改原来的值。
    Integer的值存在value属性中,Integer的hashcode就是value值。
    Integere重写了quals方法,equals()是比较value值,而不是Object的比较地址。
    Integer在进行运算,跟int进行==比较时会进行自动拆箱,因此在for循环中进行叠加运算是不太合适的(频繁拆箱影响效率),应换为其它数据类型。
    缓存部分看如下代码:
    -----------------------------
    关于缓存,看代码(jdk8):
    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() {}
    }
    在Integer类中有一个IntegerCache静态内部类,这个类在初始化的时候构造了一个涵盖区间为-128-127的Integer数组,该数组为static final的。
    Integer的valueOf()方法是将非Integer的数值转换为Integer:
    valueOf的源码:
    先判断给定的值是否在缓存区间,是直接返回缓存中的值,否则new一个新的。另外几个重载的valueOf()方法也是通过这个valueOf实现的。
    Integer的自动装箱跟拆箱就是通过这个valueOf()来实现的,因此:
    Integer a = 127;
    Integer aa = 127;
    Integer b = 128;
    Integer bb = 128;
    System.out.println(a == aa);//true
    System.out.println(b == bb);//false
    两者结果不同,原因是127在调用valueOf的时候发现在区间内会返回同一个对象,而超过127则new一个Integer,所以b跟bb是堆中的两个对象,一次为false。
    需要注意的是跟int比较的时候Integer会自动拆箱为int:
    int a = 128;
    Integer aa = 128;
    System.out.println(a == aa);//true
    频繁拆箱造成性能损耗的例子:
    Integer sum = 0;
     for(int i=1000; i<5000; i++){
       sum+=i;
    }

  • 相关阅读:
    【stanford】梯度、梯度下降,随机梯度下降
    [philosophy]空间
    【crawler】heritrix 3 使用
    【database】database domain knowledge
    【java】Java异常处理总结
    【computer theory】一、集合、关系和语言
    【java】ubuntu部署web项目war包到tomcat上
    【MachineLeaning】stanford lesson one
    【数据立方】由表和电子数据表到数据立方体,cuboid方体
    PHP变参函数的实现
  • 原文地址:https://www.cnblogs.com/nevermorewang/p/7808100.html
Copyright © 2011-2022 走看看