先上结论:
重写equals不一定要重写hashcode,特列就是在没有使用容器(集合)时
一.java规定
1.根据equals方法和hashcode规定指出,两个相同的对象的hashcode必须相同
2.两个对象相等,对两个 equals() 方法返回 true
3.两个对象有相同的 hashcode 值,它们也不一定是相等的
4.hashCode() 的默认行为是对堆上的对象的‘地址值’使用算法得到的hashcode值。如果没有重写 hashCode(),则该 class 的两个对象无论如何都不会相等(即使这两个对象指向相同的数据)。
二.举例说明
package day01;
import java.util.Objects;
public class Student {
private Long id;
public Student() {
}
public Student(Long id) {
this.id = id;
}
/**
* 获取
* @return id
*/
public Long getId() {
return id;
}
/**
* 设置
* @param id
*/
public void setId(Long id) {
this.id = id;
}
public String toString() {
return "Student{id = " + id + "}";
}
@Override
public boolean equals(Object obj) {
if(obj!=null&&!(obj instanceof Student)){
return false;
}
Student obj1 = (Student) obj;
return Objects.equals(this.id,obj1.id);
}
public static void main(String[] args) {
Student student=new Student(1L);
Student student2=new Student(1L);
Map<Student,String> map=new HashMap<>();
map.put(student,"1");
map.put(student2,"1");
System.out.println(map);
}
}
运行后得到:
运行得到:
{Student{id = 1}=1, Student{id = 1}=1}
分析:
1.我们在代码Student类中重写了equals方法,没有重写hashcode方法,重写的equals方法的逻辑是,只要我们学生的id相同,就表示是相同的对象,但是我们使用map集合装时,我们都知道map集合的键值不能相同,显然上面的结果是逻辑错误的
2.再来看我们的HashMap的源码
//put方法
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
//计算hashcode
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
//通过hash算出索引,通过索取取值==null为true,然后直接插入到索引位置
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
//新值覆盖了旧值
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
通过阅读源码,只要hash码不一样的话就可以直接插入到数组中。然而正因为我们没重写hashCode方法,所以调用的是Object的hashCode方法。而Object的hashCode是使用对象在堆中的地址通过算法得出一个int类型的值,既然如此,那刚刚创建的两个对象的int类型的值肯定是不同的,所以两个Student都可以正常插入到数组中,从而出现了逻辑错误。
3.下面重写hashcode
@Override
public int hashCode() {
//根据自己的需求写,此处是简单实例
return this.id.intValue()>>3;
}
4.再次运行后
{Student{id = 1}=1}
结果底层是student2覆盖了student,所以当重写了equals,也要重写hashcode才会达到要求。
三.反之呢?
结论:当然是要的
假设两个hashcode的两个对象,student已经put进去,student2正在进行put时,hash相同,得出的索引也是相同,就可以找到student,找到之后会继续使用equals比较,假设没有重写的话,那么就是对象地址比较,结果肯定是false,那么这个时候就发生了hash碰撞,直接挂到下面,也就形成了链表
还有在map.get(key)时也是一样都会根据hashCode找,再判断equals。
为什么要判断equals呢?因为根据hashCode找到的是一个链表,需要根据equals在链表中找到Key相等的那个值。