==、equals、hashcode

[TOC]

区别

对于基本类型,== 判断两个值是否相等,基本类型没有 equals() 方法。
对于引用类型,== 判断两个变量是否引用同一个对象,而 equals() 判断引用的对象是否等价。

1
2
3
4
Integer x = new Integer(1);
Integer y = new Integer(1);
System.out.println(x.equals(y)); // true
System.out.println(x == y); // false

为什么重写equals需要重写hashcode?

hashCode() 返回散列值,而 equals() 是用来判断两个对象是否等价。等价的两个对象散列值一定相同,如果不重写hashcode的话,会导致等价的两个对象散列值不相同 (由于默认的hashcode方法是根据对象的内存地址经哈希算法得来的,故两者的hashcode不一定相等) 。因此在覆盖 equals() 方法时应当总是覆盖 hashCode() 方法。