简介
Map接口:双列数据,存储key-value对的数据
- HashMap:作为Map的主要实现类,线程不安全,效率高;可以存储key-value都为null
- LinkedHashMap:HashMap的子类,在HashMap底层原理上,添加一对指针,指向前一个和后一个元素,对于频繁的遍历操作,效率高于HashMap。(遍历map元素是,可以按照添加顺序遍历)
- TreeMap:保证按照添加的key-value对进行排序,实现遍历操作,考虑key的自然排序和定制排序。底层红黑树
- Hashtable:作为古老的实现类,线程安全,效率低,不能存储key-value任意为null
- Properties:Hashtable的子类,常用来处理配置文件,key-value都是String类型
一、HashMap底层实现原理描述
1. jdk7
- Map map = new HashMap();实例化以后,底层创建长度为16的数组Entry[] table。
- map.put(key1,value1);调用key1所在类的hashCode()方法计算哈希值出code。
- 此哈希值通过某种算法(code & (16 -1)),可以理解为取模,计算出在数组table中的存放位置(数组下标)
- 如果此位置的数据为空,则此时的key1-value1添加成功
- 如果此位置上的数据不为空,(意味着此位置上存在一个key2或者多个(单向链表形式)),比较哈希值
①如果hash值不相同,则肯定不是相同对象,添加成功。 ②如果hash相同,则比较key1和key2的的equals()方法,返回false,添加成功。返回true,value1替换value2 ③以上两种方式以单向链表的方式存储 - 新添加的元素放到数组中,指向原来的元素。(next = 原来数据)
- 默认扩容方式:扩容为原来的2倍,并将原有的数据复制过来
- 底层结构:数组+单向链表
2. jdk8
- Map map = new HashMap();实例化以后,底层没有创建默认长度数组。
- jdk8底层是Node[]数据,而非Entry;只是改了个名字。
- 底层结构:数组+单向链表+红黑树
- 扩容及红黑树:当某一个索引上的元素以单向链表形式存在数据 > 8 且当前数据长度 > 64时,此索引上的以单向链表形式的元素改为使用红黑树存储。
二、HashMap源码的重要常量
- DEFAULT_INITIAL_CAPACITY:HashMap的默认容量,16
- MAXIMUM_CAPACITY:HashMap的最大支持容量,2的30次方
- DEFAULT_LOAD_FACTOR:Bucket中链表长度大于该默认值,转化为红黑树
- UNTTREEIFY_THRESHOLD:Bucket中红黑树存储的Node小于该默认值,转为链表
- MIN_TREEIFY_CAPACITY:桶中的Node被树化时最小的hash表容量。(当桶中的Node数量大到需要变红黑树时,若hash表容量小于MIN_TREEIFY_CAPACITY时,此时应执行resize扩容操作这个MIN_TREEIFY_CAPACITY的值至少是TREEIFY_THRESHOLD的4倍)
- table:存储元素的数组,总是2的n次幂
- entrySet:存储具体元素的集
- size:HashMap中存储的键值对的数量
- modCount:HashMap扩容和结构改变的次数
10.threshold:扩容的临界值 = 容量 * 填充因子 11.loadFacTor:填充因子
三、JDK7源码
1、Map map = new HashMap() 实例化
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
this.loadFactor = loadFactor;
threshold = initialCapacity;
init();
}
2、put操作
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null) return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
3、添加操作
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
4、创建操作
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
三、JDK8源码
1、Map map = new HashMap()
static final float DEFAULT_LOAD_FACTOR = 0.75f;
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
}
2、put操作
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
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)
n = (tab = resize()).length;
if ((p = 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)
treeifyBin(tab, hash);
break;
}
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold) ()resize();
afterNodeInsertion(evict);
return null;
}
3、初始化及扩容
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1;
}
else if (oldThr > 0)
newCap = oldThr;
else {
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
....
return newTab;
}
四、HashMap方法
1、get()方法
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 && ((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;
}
2、keySet()方法
public Set<K> keySet() {
Set<K> ks = keySet;
if (ks == null) {
ks = new KeySet();
keySet = ks;
}
return ks;
}
final class KeySet extends AbstractSet<K> {
public final int size() { return size; }
public final void clear() { HashMap.this.clear(); }
public final Iterator<K> iterator() { return new KeyIterator(); }
public final boolean contains(Object o) { return containsKey(o); }
public final boolean remove(Object key) {
return removeNode(hash(key), key, null, false, true) != null;
}
public final Spliterator<K> spliterator() {
return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0);
}
public final void forEach(Consumer<? super K> action) {
Node<K,V>[] tab;
if (action == null)
throw new NullPointerException();
if (size > 0 && (tab = table) != null) {
int mc = modCount;
for (Node<K,V> e : tab) {
for (; e != null; e = e.next)
action.accept(e.key);
}
if (modCount != mc)
throw new ConcurrentModificationException();
}
}
}
final class KeyIterator extends HashIterator
implements Iterator<K> {
public final K next() { return nextNode().key; }
}
- ks = new KeySet();ks获取到KeySet()
- KeySet对象重写了Iterator方法
- KeyIterator获取元素的下一个key
- map.keySet()只是个空对象,debug可以看到是因为toString()方法调用遍历的。
|