您的位置:首页 > 编程语言 > Java开发

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

2017-06-23 16:11 260 查看
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方法进行比较
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java integer