equals()
- 等价关系
两个对象具有等价关系,需要满足以下五个条件:
自反性
a.equals(a);//true
对称性
a.equals(b)==b.equals(c);//true
传递性
if (x.equals(y) && y.equals(z))
x.equals(z); // true;
一致性
x.equals(y) == x.equals(y); // true
与 null 的比较:对任何不是 null 的对象 x 调用 x.equals(null) 结果都为 false
x.equals(null); // false;
- 等价与相等
- 对于基本类型,== 判断两个值是否相等,基本类型没有 equals() 方法。
- 对于引用类型,== 判断两个变量是否引用同一个对象,而 equals() 判断引用的对象是否等价
Integer x = new Integer(1);
Integer y = new Integer(1);
System.out.println(x.equals(y)); // true
System.out.println(x == y); // false