int和Integer的区别

本文详细解析了Java中int与Integer的区别,包括基本数据类型与封装类的概念、默认值的不同,以及实例化与自动装箱拆箱的过程。通过源码分析了Integer缓存机制,解释了特定情况下的对象比较结果。

int和Integer

基本区别
  • 首先int是八大基本数据类型其中的一员,Integer是封装了方法的类
  • Integer既然是类那么就必须实例化,而int是不要实例化的
  • Integer默认值是null,int的默认值是0
操作实例
public static void main(String[] args) {
    Integer i = new Integer(100);
    int i1 = 100;
    System.out.println(i==i1);//true 此处自动拆箱与int i1进行值比较

    Integer i2 = new Integer(100);
    Integer i3 = new Integer(100);
    System.out.println(i2==i3);//false new出的新对象地址肯定是不相等的

    Integer i4 = 100;
    Integer i5 = 100;
    System.out.println(i4==i5);//true 会翻译成为Integer i = Integer.valueOf(100),Integer会缓存-128到127之间的整数值

    Integer i6 = new Integer(100);
    Integer i7 = 100;
    System.out.println(i6==i7);//false i7指向的是常量池中的100,而i6是重新new了一个新的对象
源码参考
public static Integer valueOf(int i) { //解释成valueOf方法
    if(i >= -128 && i <= IntegerCache.high)
        return IntegerCache.cache[i + 128];
    else
        return new Integer(i);
}
private static class IntegerCache {
    static final int high;
    static final Integer cache[];

    static {
        final int low = -128;

        // high value may be configured by property
        //默认最大值,可以自定义
        int h = 127;
        if (integerCacheHighPropValue != null) { 
            // Use Long.decode here to avoid invoking methods that
            // require Integer's autoboxing cache to be initialized
            int i = Long.decode(integerCacheHighPropValue).intValue();
            i = Math.max(i, 127);
            // Maximum array size is Integer.MAX_VALUE
            h = Math.min(i, Integer.MAX_VALUE - -low);
        }
        high = h;

        cache = new Integer[(high - low) + 1];
        int j = low;
        for(int k = 0; k < cache.length; k++)
            cache[k] = new Integer(j++);
    }

    private IntegerCache() {}
}
private static String integerCacheHighPropValue;//保存缓存

    static void getAndRemoveCacheProperties() {
        if (!sun.misc.VM.isBooted()) {
            Properties props = System.getProperties();
            integerCacheHighPropValue =
                (String)props.remove("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null)
                System.setProperties(props);  // remove from system props
        }
    }
总结

通过源码就能够解释第三个例子为什么为true了,-128至127这个特殊区间划重点

尽可能使用包装类,其中内置方法能够在业务中便捷处理数据,不然需要多一步数据处理过程

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值