- ArrayList内部是一个数组的数据结构
- LinkedList内部是一个链表的数据结构
- TreeMap 内部是一个二叉树的数据结构(没用过)
- HashMap内部是数组加链表,在java1.8之后,当链表达到一定长度之后,会转换成红黑树。
HashMap 是怎么存数据的?
- 当第一次调用put方法添加数据的时候,会先进行数组的初始化操作。
- 调用put方法的时候,会先对key进行hash运算,然后再对当前值在进行一次取模运算,比如当前数组长度是5,key进行hash运算之后是6,那么会再进行6%5,余数是1,把当前元素存在数组的是1个位置上。即a[1]。
取余(取模)有个规律就是:左边小于右边,结果为左边,左边大于右边,看余数
- 如果经过hash运算后,得到的值小于数组的长度,那么直接存储到当前数组中,如果数组中已经存在元素了,也就是发生率hash碰撞,这个时候key如果不同的话,就以链表的形式,链接到当前元素的后一个位置。如果key相同的话,会把当前的value值进行替换,并且把旧的value值返回。
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
- Map集合内部Entry类,他内部就是包含我们存入元素的Key,value,next,以及hash值。
Hashmap是怎么取元素的?
public V get(Object key) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? null : e.value;
}
/**
* Implements Map.get and related methods
*
* @param hash hash for key
* @param key the key
* @return the node, or null if none
*/
final Node<K,V> getNode(int hash, Object key) {
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
if ((tab = table) != null && (n = tab.length) > 0 &&
(first = tab[(n - 1) & hash]) != null) {
if (first.hash == hash && // always check first node
((k = first.key) == key || (key != null && key.equals(k))))
return first;
if ((e = first.next) != null) {
if (first instanceof TreeNode)
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
do {
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
} while ((e = e.next) != null);
}
}
return null;
}
HashMap是什么时候开始扩容的?
当个数达到设定的阈值时候。
if (++size > threshold)
resize();