- public class SLI_IntegerTest {
- public static void main(String[] args) {
- Integer a= new Integer(1000);
- Integer b= new Integer(1000);
- System.out.println(a==b);
- //输出结果false
- //==是对象引用的比较,明显是两个不同的对象,所以不相等
- System.out.println(a.equals(b));
- //输出结果true
- //Integer已经重载了equals方法,实现如下:
- // public boolean equals(Object obj) {
- // if (obj instanceof Integer) {
- // return value == ((Integer)obj).intValue();
- // }
- // return false;
- // }
- //可以看出Integer的equals方法实际是执行内部intValue的比较,所以只要里面存放的值相等,就会返回true
- System.out.println(a==1000);
- //输出结果true
- //原因是在做==比较时,变量a会做自动拆箱(unbox)操作,把自己变成基本类型,然后比较,auto box/unbox功能是java1.5新引进的
- Integer c= 1000;//自动装箱(box)操作,基本类型int 1000可以自动box成对象Integer
- Integer d= 1000;//自动装箱(box)操作,基本类型int 1000可以自动box成对象Integer
- System.out.println(c==d);
- //输出结果false
- //两个不同的对象,所以不相等
- Integer e= 100;
- Integer f= 100;
- System.out.println(e==f);
- //那么这个输出结果到底是什么呢?可以想一想,然后再试一试
- }
- }