int 和 Integer 有什么区别?谈谈 Integer 的值缓存范围。

如何回答 ?

该问题从几个方面来回答:

  1. 定义(本质区别)
  2. 值的比较
  3. 所占内存

1. 定义

int

它是 基本类型,是java的 8 个基本类型之一。

Integer

int 的包装 ,它有一个 private final int 类型字段来存储值。并且提供了基本操作,如:数字运算,int 和字符串之间转换等。

JAVA5 对 Integer 的优化:
  1. 引入装箱拆箱功能(boxing/unboxing), java 根据上下文,自动转换。
  2. 引入值缓存,新增静态工厂方法 valueOf,调用时利用缓存机制,默认的缓存值是 -128 到 127之间。(需要特别注意:从源码上看,默认值是 -128 到 127,这里的最大值是可以修改的,这个在大部分网上的总结资料中都没谈及,下面会在文章中解释
public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

2. 值的比较

  1. int 基本类型直接用 == 比较
  2. Integer 是对象,直接 == 是比较引用地址,需要用 equals 进行比较。Integer.equals() 源码:
public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }
  1. Integer 缓存范围内的值,比对相同数值时, == 为 true。当值为 缓存范围外的值,由于会 new 新对象, == 为 false。缓存值默认值为 [-128,127],但是也可以通过修改 jvm 配置来修改其最大值。
    1. IntegerCache 源码:
    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 =
                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() {}
    }
    
    1. 从源码可以看出,缓存最大值受 java.lang.Integer.IntegerCache.high 影响,而修改 java.lang.Integer.IntegerCache.high 值的方式有两个配置:
    -Djava.lang.Integer.IntegerCache.high=<size>
        或者 
    -XX:AutoBoxCacheMax=<size>
    

3. 所占内存

Integer 是对象,比基本类型所占内存要多。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Charlven

你的鼓励将是我最大的动力哦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值