hashmap底层是一个数据,实际是node 数组加链表,他的初始容量是2*4次方16是在第一次添加数据的时候初始化的容器,每一个数据中的node节点参数有hash,k,v以及下一个node的引用属性。
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
Node(int hash, K key, V value, Node<K,V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
public final K getKey() { return key; }
public final V getValue() { return value; }
public final String toString() { return key + "=" + value; }
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
public final boolean equals(Object o) {
if (o == this)
return true;
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue()))
return true;
}
return false;
}
}
插入的时候:通过hash算法然后取模获得在数组的索引位置存入数据,如果发生hash冲突则用前一个node的属性next指向当前的插入的数据
查询的时候:通过hash算法获取到数组索引位置,然后用hash比较看是否为同一个对象
如果不是就看下一个next,当hash值相同时则去拿当前的key比较是否相同
红黑树实际时为了加快查询速度
当链表长度超过8的时候会调用treeifbin方法转成红黑树
hashmap和hashtable的区别:
·1、继承不同
2、hashtable是线程安全的
3、Hashtable中,key和value都不允许出现null值
4、HashTable中的hash数组初始大小是11,增加的方式是 old*2+1。HashMap中hash数组的默认大小是16,而且一定是2的指数。