一、概述:
上述博客中我们已经了解到:当HashSet的泛型为自定义类(Student类)时,当我们向其中添加重复的具有相同属性(id)的的对象时,由于地址的不同,会导致hashCode和hash值的不同,最终导致具有相同属性(id)的对象的添加成功 ,这显然不符合我们要求的id的唯一性原则。所以我们需要对hashCode方法进行重写。
二、实现方法及代码分析:
1.在自定义类中重写父类的hashCode方法,让其返回id的hashCode值:
package com.practice;
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
@Override
public int hashCode() {
return id.hashCode();
}
}
2.当我们再次向set中添加具有相同id的对象时:
package com.wjm.practice4;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<Student> set = new HashSet<Student>();
set.add(new Student("123"));
set.add(new Student("123"));//改行代码如何执行?
}
}
3.add方法的底层代码为:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
4.add方法中的put方法底层代码为:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
5.put方法中的hash方法如下,由于我们重写了Student中的HashCode方法,所以这次的hashCode值与第一次存储时的相同,因此hash值也相同:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
6.put方法中的putVal方法如下:
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)//由于存第一个对象时table全局变量已经有值了,所以tab不为空且tab.length不等于0,所该if为false,n为16
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)// i = (n - 1) & hash 为(数组长度-1) & hash 的值,即(16-1) & hash,因为第一个和第二个值的hash方法返回值相同,所以存第一个值和存第二个值的时候(n - 1) & hash的值是一样的 ,所以存第二个对象时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))))// p.hash == hash 为 true, (k = p.key) == key 为 false (key != null && key.equals(k)) 因为学生类没有重写equals,所以调用Object类中equals 比较的是地址 false
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;
}
总结:虽然我们重写了hashCode方法,但是并未重写equals方法,因此具有重复属性的对象依然会存储成功。