- 首先,我们先来看下面一段代码:
package set;
import java.util.HashSet;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
HashSet<String> set=new HashSet<String>();
set.add("Tom");
set.add("Tom");
}
}
在讲HashSet的常用方法时我们已经知道了HashSet不能添加重复的元素,下面我们来看add方法的底层代码,讲add方法具体是怎么执行的,在这里我们需要思考的一个问题是,add方法在执行的时候,是怎么判断不允许重复的。
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
在这里,我们可以看到,HashSet<String> set = new HashSet<String>();//创建HashSet对象,调用了该类中无参构造方法——>执行了该构造方法中map = new HashMap<>();——>map为HashSet全局变量
public HashSet() {
map = new HashMap<>();
}
此时我们按着ctrl键点击add,可以看到add的执行代码:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
在这里接着点击put,有:
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);//执行putVal方法,先执行hash(key)
}
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)//创建HashSet——》new HashMap ——》table=null//第二次添加“Tom”时,此处为false
n = (tab = resize()).length;//这时第一次添加“Tom”时,resize返回了一个newTab,这时table和tab都指向这个开辟的新数组的空间,tab和table指向同一个地址,这是因为在resize中,
if ((p = tab[i = (n - 1) & hash]) == null)//n=16;//第二次添加"Tom"时,由于此时二者的hash值相同,所以对应的tab[i]为第一次tab[i]被赋的值,不为null,此处为false
tab[i] = newNode(hash, key, value, null);//此时给数组中的一个元素赋值,这时需要注意的是,i不一定是从0开始的,此时即为添加第一个元素"Tom",由于tab和table指向同一个地址,所以此时的table[i]也是有值的
else {
Node<K,V> e; K k;
if (p.hash == hash //此时成立&&
((k = p.key) == key //此时成立|| (key != null && key.equals(k))))
e = p;//所以就将p的值赋给了e
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) { //此时该条件为true,则有第二次添加Tom的返回值为oldValue,则 return map.put(e, PRESENT)==null;返回false,即为添加失败
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;//第二次添加Tom确实覆盖了第一次添加的Object常量,但是还是原来的Node对象,只是其value属性发生了变化——被第二个Object常量覆盖了
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;//第一次return null,则 return map.put(e, PRESENT)==null;即为true,即添加成功
}
- hash方法如下:
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- 此时我们可以看到在hash方法里调用了hashCode方法:
- hashCode();在Object中是得到对象的地址,在String类里面返回的则是对象的内容
同时,在这里key是一个String类型,而 Object key此处key就为上转型,因此这里的key.hashCode()表面上是调用父类Object的hashCode方法,实际上是调用key的String类的hashCode方法:
Object的hashCode方法:
public native int hashCode();<