Int和Integer的一些区别和技术点

 

        int i=127;
        Integer i2=127;
        Integer i3=new Integer(127);
        //打印hashCode
        System.out.println(System.identityHashCode(i));
        System.out.println(System.identityHashCode(i3));
        
        System.out.println(i==i2);
        System.out.println(i==i3);
        System.out.println(i2==i3);

结果 

1705736037
455659002
true
true
false

这里i==i3为true ,开始没有弄清楚,因为i3是new 出来的 讲道理的他们的地址是不同的 所有应该为false 但是后来问了老师在查询了一些资料发现,int 和 Integer进行比较时,Integer会自动拆箱调用intValue()方法返回一个int值,这个时候两个int值指向都是同一个栈中的地址,所以他们是true.

i2==i3 false是因为 Integer和Integer进行比较的时候并不会进行拆箱所以他们地址不一样为flase

大家都知道Integer是int的包装类,1.5后进行了自动装箱,和自动拆箱的操作;

Integer a = 128;
//编译后的class文件中
Integer a = Integer.valueOf(128);

//这里会调用Integer.valueOf  返回表示指定的 int值的 Integer实例。 


  方法源代码:

  public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)  //判断值是否在-128和127之间
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

这里有一个IntegerCache是Integer 中的静态内部类,这里我贴一部分源码出来

 private static class IntegerCache {
        static final int low = -128;//这里可以看出最小值是-128
        static final int high;       //最大值在下面被赋值为127
        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  如果你的值在-128到127之间会被缓存到IntegerCache.cache这个数组中,如果下次进行创建会直接返回调用缓存中的值,如果你的值大于127那么就会重新new Integer()。最大边界可以通过-XX:AutoBoxCacheMax进行配置,但也不会大于Integer.MAX_VALUE最大值(2^31次方,2147483648,正21亿多)。


为什么要这样做?

我们仔细想想, 淘宝的商品大多数都是100以内的价格, 一天后台服务器会new多少个这个的Integer, 用了IntegerCache,就减少了new的时间也就提升了效率。同时JDK还提供cache中high值得可配置,这无疑提高了灵活性,方便对JVM进行优化。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值