Map 是一种数据结构,用来实现key和value 的映射。通过Key可以找到Value。实现类包括
HashMap,LinkedHashMap,TreeMap
/**
* Applies a supplemental hash function to a given hashCode, which
* defends against poor quality hash functions. This is critical
* because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits. Note: Null keys always map to hash 0, thus index 0.
*/
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* Returns index for hash code h.
*/
static int indexFor(int h, int length) {
return h & (length-1);
}
/**
* Associates the specified value with the specified key in this map.
* If the map previously contained a mapping for the key, the old
* value is replaced.
*
* @param key key with which the specified value is to be associated
* @param value value to be associated with the specified key
* @return the previous value associated with <tt>key</tt>, or
* <tt>null</tt> if there was no mapping for <tt>key</tt>.
* (A <tt>null</tt> return can also indicate that the map
* previously associated <tt>null</tt> with <tt>key</tt>.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
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;
}
HashMap 是以数组的结构,用哈希函数值跟数组的长度做位与运算,获取对应数组的索引。浏览key值时,不保证顺序。
LinkedHashMap 是以双向列表的结构做实现的,浏览key值时候,可以保证顺序。LinkedHashMap继承HashMap ,不同的是数据存储结构。
TreeMap 是以二叉树实现的Map接口。Map中的key值按照从小到大的顺序排列。key要实现comparable
TreeMap 是用二叉树结构存储的,根据key找value的时间复杂度是o(以2为底,n的对数)
查找和插入的性能都没有hashmap好,但是可以实现key的有序存放。所以增加了hashMap的类。
二叉树的中序遍历就是从小到大的顺序排列。