Integer封装类对象的比较(==,equals)

这篇博客探讨了在Java中,对于通过`new`创建和自动装箱产生的Integer对象,如何使用`==`和`equals()`进行比较。内容详细解析了Integer类中的equals方法重写以及valueOf方法的工作原理,特别是Integer缓存机制对于小数值比较的影响。当数值在-128到127之间时,`==`和`equals()`都会返回True,而超出此范围则可能返回False。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先讨论通过new出来的对象如何比较

=====================================================

public class TestInteger02 {
    public static void main(String[] args) {
        Integer integer01=new Integer(12);
        Integer integer02=new Integer(12);
        //将两者用==进行比较
        System.out.println(integer01==integer02);//因为两者为不同对象,所以地址不同,false

    }
}

==的比较,两个封装类的对象地址不相同,故输出false

public class TestInteger02 {
    public static void main(String[] args) {
        Integer integer01=new Integer(12);
        Integer integer02=new Integer(12);
        System.out.println(integer01.equals(integer02));
    }
}

equals方法的比较,输出为true,

说明Integer封装类中的equals方法是重写了Object类中的equals方法,因为原来的equals方法和==是同样的用法

public boolean equals(Object obj) {
        if (obj instanceof Integer) {
            return value == ((Integer)obj).intValue();
        }
        return false;
    }

进入Integer方类中查看重写的equals方法,发现将equals重写成了值的比较,此时调用equals方法比较的是两者在底层封装的value的值
//public static final value(Integer类中的封装静态属性),也是构造器传入的值

================================================================================================================
接下来讨论通过自动装箱产生的Integer类的对象,两者比较结果是否相同呢?

public class TestInteger02 {
    public static void main(String[] args) {
        Integer integer01=12;
        Integer integer02=12
        System.out.println(integer01.equals(integer02));//True
    }
}

发现两者调用equals方法相等,因为之前讲过Integer类将equals方法改成对value值的比较,所以没什么问题

public class TestInteger02 {
    public static void main(String[] args) {
        Integer integer01=12;
        Integer integer02=12;
        System.out.println(integer01==integer02);//True
    }
}

接着用==来比较两者,发现输出结果为True,为什么会出现这样的结果?

实际上这和自动装箱的原理有关,在自动装箱的时候调用了valueof()方法

这时候打断点,debug进入Integer类中查看valueof方法

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

接下来,在按住ctrl点击IntegerCache.low查看具体,进入Integer这个内部类中

private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer[] cache;
        static Integer[] archivedCache;

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    h = Math.max(parseInt(integerCacheHighPropValue), 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(h, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            // Load IntegerCache.archivedCache from archive, if possible
            VM.initializeFromArchive(IntegerCache.class);
            int size = (high - low) + 1;

            // Use the archived cache if it exists and is large enough
            if (archivedCache == null || size > archivedCache.length) {
                Integer[] c = new Integer[size];
                int j = low;
                for(int i = 0; i < c.length; i++) {
                    c[i] = new Integer(j++);
                }
                archivedCache = c;
            }
            cache = archivedCache;
            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

通过阅读代码发现low的值为-128,需要获取high的信息,于是再把静态块中有用的信息提取出来

int h = 127;
        high = h;
        int size = (high - low) + 1;
        // Use the archived cache if it exists and is large enough
        
            Integer[] c = new Integer[size];
            int j = low;
            for (int i = 0; i < c.length; i++) {
                c[i] = new Integer(j++);
            }
        

int size = (high - low) + 1; //high通过阅读告诉我们是127,则size=256
Integer[] c = new Integer[size];//新建一个Integer数组c,数组长度为256

int j = low;
//这三行代码是通过for循环给c数组赋值
for (int i = 0; i < c.length; i++) {
c[i] = new Integer(j++);
}

c【0】=-128
c【1】=-127

c【255】=127

================
此刻再回过头来看valueof方法

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
    }

其中的if条件即为:

if(i>=-128&&i<=127)
		return IntegerCache.cache[i-(-128)]//此时返回的是cache数组里的值
return new Integer(i)//超出范围的数则直接封装为对象,因为不在数组中取不到值

所以

public class TestInteger02 {
public static void main(String[] args) {
Integer integer01=12;
Integer integer02=12
System.out.println(integer01.equals(integer02));//True
}
}
两者值为12时候,能在数组中取到值,比较的是两者的值,则为True
而两者如果为300时候,在数组中取不到值,则调用valueof方法返回的是两个对象,两个对象地址自然不相同,故为false

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值