Integer Integer.valueOf和Integer.

2020-08-06  本文已影响0人  王兴岭

Integer

Integer是int的包装类,在Integer中有个常量池类IntegerCache,在 IntegerCache中会创建一个cahce数组,默认情况下会将-128到127
的Integer对象提前创建好,然后放到cache数组中,当使用Integer.valueOf将int转成Integer时,Integer会判断当前数值的范围是不是在[-128, 127]之间,如果在,则直接从常量池中取,如果不在,则调用Integer构造器创建新的Integer

private static class IntegerCache {
        // 最小值-128
        static final int low = -128;
        //最大值没有直接写死127,而是可以通过系统配置设置high,而且不能小于127,不能大于int的最大值
        static final int high;
        static final Integer cache[];
       //利用类的延迟加载机制,只要Integer第一次使用IntegerCache才会加载IntegerCache类并调用static静态方法,以达到延迟加载的目的.
        static {
            // high value may be configured by property
            // 默认high为127
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    //Math.max 如果配置的值小于127,则用127
                    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
            high = h;
            //创建cache数组
            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                 //创建[-128,127]Integer对象放在cache数组中
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }
       //私有构造器,禁止外部的对象创建
        private IntegerCache() {}
    }

1. Integer.valueOf

public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
}

public static Integer valueOf(int i) {
         //判断i的大小是不是在[-128,127]之间,如果是则直接从cache缓存中取,节省了对象创建的时间
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        //如果不在[-128,127]之间,那就直接创建Integer对象
        return new Integer(i);
}

Demo Test

public class IntegerTest {

  public static void main(String[] args) {
    
    Integer a = 1;//等价Integer.valueOf(1)
    Integer b = 1;
     //走了Integer常量池,输出为true
    System.out.println(a==b);
 
    Integer h = new Integer(1);
    Integer j = new Integer(1);
   //创建新Integer对象,输出为false
    System.out.println(h==j);
    Integer c = 300;
    Integer d = 300;
    //300超出[-128,127]所以是从新创建的对象,故c==d为false
    System.out.println(c==d);
  }
}

控制台输出

true
false
false

2 parseInt

public static int parseInt(String s) throws NumberFormatException {
        return parseInt(s,10);
}

parseInt功能很简单,就是把字符串转换成10进制的数值.而且返回值是int,而不是Integer,这个要注意.

上一篇下一篇

猜你喜欢

热点阅读