一、概述:
根据前面的博客中我们可知当泛型为String时,向HashSet对象中添加一个同已有元素相同的元素会添加失败,本博客继续深入讨论当泛型是自定义类时的情况。
二、代码分析:
1.首先我们创建一个自定义类Student:
package com.practice;
public class Student {
private String id;
public Student(String id) {
this.id = id;
}
}
2.以该自定义类为泛型,创建HashSet对象并向其中添加两个具有相同id的对象,我们讨论第二次添加学生对象时该代码的底层代码如何执行:
package com.practice;
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()方法如下,由于第二次存入的对象和第一次存入的对象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,因为第一个和第二个值的hashCode不相同,所以存第一个值和存第二个值的时候(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))))
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)// onlyIfAbsent本来就为false,所以!onlyIfAbsent为true
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
总结:如果HashSet的泛型为自定义类,即使向set中添加与之前对象具有相同属性的对象时,由于他们的地址不同,hashCode就不同,hash值也就不同,这会导致具有重复属性的对象添加成功