Integer 类型数据比较相等的那些坑

本文通过实例详细解析了 Java 中 Integer 对象之间的各种比较方式及其结果,强调了使用 equals 方法进行对象比较的重要性。

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

public void testInter() {
    Integer a = new Integer(200);
    Integer b = new Integer(200);
    Integer c = 200;
    Integer e = 200;
    int d = 200;
    Object o=200;
    System.out.println("基本类型和数字常量    ==判断"+(o==c));
    System.out.println("基本类型和数字常量    equal判断"+c.equals(o));
    System.out.println("两个new出来的对象    ==判断" + (a == b));
    System.out.println("两个new出来的对象    equal判断" + a.equals(b));
    System.out.println("new出的对象和用int赋值的Integer   ==判断" + (a == c));
    System.out.println("new出的对象和用int赋值的Integer   equal判断" + (a.equals(c)));
    System.out.println("两个用int赋值的Integer    ==判断" + (c == e));
    System.out.println("两个用int赋值的Integer    equal判断" + (c.equals(e)));
    System.out.println("基本类型和new出的对象   ==判断" + (d == a));
    System.out.println("基本类型和new出的对象   equal判断" + (a.equals(d)));
    System.out.println("基本类型和自动装箱的对象   ==判断" + (d == c));
    System.out.println("基本类型和自动装箱的对象   equal判断" + (c.equals(d)));
}
//Java代码执行结果
基本类型和数字常量    ==判断false
基本类型和数字常量    equal判断true
两个new出来的对象    ==判断false
两个new出来的对象    equal判断true
new出的对象和用int赋值的Integer   ==判断false
new出的对象和用int赋值的Integer   equal判断true
两个用int赋值的Integer    ==判断false
两个用int赋值的Integer    equal判断true
基本类型和new出的对象   ==判断true
基本类型和new出的对象   equal判断true
基本类型和自动装箱的对象   ==判断true
基本类型和自动装箱的对象   equal判断true

综上代码测试后发现无论什么比较,Integer类型的数据最好用equals方法进行比较
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值