不止是Integer,Long,Float等都存在对象缓存机制,比如Integer的缓存值在于-128——127,如果使用自动装箱,则在这个范围内的对象引用是相等;
但如果是new出来的,因为是新开创空间,即使是在这个范围内,也是不相等的;
测试如下:
Integer a = 500;
Integer b = 500;
Integer c = 127;
Integer d = 127;
Integer e = new Integer(127);
Integer f =new Integer(127);
System.out.println(a == b);//false
System.out.println(a.equals(b));//true
System.out.println((c==d));//true
System.out.println(c.equals(d));//true
System.out.println(e==d);//false
System.out.println(e.equals(d));//true
System.out.println(e==f);//false
System.out.println(e.equals(f));//true
只要值相等,equals都是相等的,因为在基本类型的包装类中都对于equals进行重写,如Integer对于equals进行重写,先将对象通过intValue()转成基本数据类型,然后再用"=="进行比较的;
- 而其它没有重写equals()方法的类,比如我们自己定义的类,在使用equals()方法时,都是调用Object类的equals(),最终用"=="比较地址;