java集合之 Map

来源:互联网 发布:淘宝店网址在哪里 编辑:程序博客网 时间:2024/06/15 08:15

Map是java中常用的接口。
Map所有的子接口:

Bindings, ConcurrentMap<K,V>, ConcurrentNavigableMap<K,V>, LogicalMessageContext, MessageContext, NavigableMap<K,V>, SOAPMessageContext, SortedMap<K,V>

所有实现该接口的实现类

AbstractMap, Attributes, AuthProvider, ConcurrentHashMap, ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap

今天我们先来看看最常用的两个实现类HashMap和LinkedHashMap。
我们先看下这两个类之间的关系。
这里写图片描述

HashMap

实现类从源码上看
先看put方法:

public V put(K key, V value) {    return putVal(hash(key), key, value, false, true);}/**     * Implements Map.put and related methods     *     * @param hash hash for key     * @param key the key     * @param value the value to put     * @param onlyIfAbsent if true, don't change existing value     * @param evict if false, the table is in creation mode.     * @return previous value, or null if none     */    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) // -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) { // existing mapping for key                V oldValue = e.value;                if (!onlyIfAbsent || oldValue == null)                    e.value = value;                afterNodeAccess(e);                return oldValue;            }        }        ++modCount;        if (++size > threshold)            resize();        afterNodeInsertion(evict);        return null;    }    最后执行到了afterNodeAccess()或者afterNodeInsertion(),    这两个接口皆是LinkedHashMap类的方法;    // Callbacks to allow LinkedHashMap post-actions    void afterNodeAccess(Node<K,V> p) { }    void afterNodeInsertion(boolean evict) { }我们再看这两个方法    void afterNodeInsertion(boolean evict) { // possibly remove eldest        LinkedHashMap.Entry<K,V> first;        if (evict && (first = head) != null && removeEldestEntry(first)) {            K key = first.key;            removeNode(hash(key), key, null, false, true);        }    }    void afterNodeAccess(Node<K,V> e) { // move node to last        LinkedHashMap.Entry<K,V> last;        if (accessOrder && (last = tail) != e) {            LinkedHashMap.Entry<K,V> p =                (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;            p.after = null;            if (b == null)                head = a;            else                b.after = a;            if (a != null)                a.before = b;            else                last = b;            if (last == null)                head = p;            else {                p.before = last;                last.after = p;            }            tail = p;            ++modCount;        }    }

我们发现, 最后key和value都是存放在了LinkedHashMap.Entry(),也就是说,Entry是键和值最后的归宿。

在使用put方法的时候,首先调用的是hash方法生成hashCode,

1.无序;
无序是因为HashMap的底层实现使用的数组,数组的下标是和hash值相关的,而hash值是无序的所以决定了hashMap是无序的。
2.非线程安全;
在put时没有使用同步操作,在多线程编程的情况下,就会出现问题。(有个疑问,hashmap有解决hashCode冲突的机制,那为什么还会有线程不安全的情况出现)
3.键值对允许为null;

解决hashCode冲突:
虽然HashMap的底层实现使用的数组,但是数组内的元素并不是简单的值,而是一个Entry对象,如下图所示:
这里写图片描述

可以看到HashMap的内部维护着一个Entry数组,每一个Entry表项包括key、value、next、hash。这里特别注意,其中next,它指向一个Entry。通过解析HashMap的put( )方法,可以看到当put( )有冲突时,新的Entry依然会被安放在对应的索引下标内,并替换原有的值。同时,为了保证旧值不丢失,会将新的Entry的next指向旧指,这便实现了,在一个数组索引空间内存放多个值项。

负载因子
除hashCode( )的实现外,影响HashMap性能的还有还有它的容量参数。和ArrayList和Vector一样,这种基于数组的结构,不可避免的需要在数组空间不足时,进行扩容。而数组的重组相对而言较为耗

其中initialCapacity指定了HashMap的初始容量,loadFactor指定了其负载因子。初始容量即数组的大小,HashMap会使用大于等于initialCapacity并且是2的指数次幂的最小整数作为内置数组的大小(比如,传入initialCapacity的参数为10,2^3 = 8 < 10 < 2^4 = 16,则16作为内置数组的初始化容量)。负载因子又叫做填充比,它是介于0和1之间的浮点数,它决定了HashMap在扩容之前,其内部数组的填充度。默认情况下HashMap初始容量为16,负载因子为0.75。

负载因子 = 元素个数 / 内部数组总大小

HashTable

进入HashTable类,

public synchronized V put(K key, V value) {        // Make sure the value is not null        if (value == null) {            throw new NullPointerException();        }        // Makes sure the key is not already in the hashtable.        Entry<?,?> tab[] = table;        int hash = key.hashCode();        int index = (hash & 0x7FFFFFFF) % tab.length;        @SuppressWarnings("unchecked")        Entry<K,V> entry = (Entry<K,V>)tab[index];        for(; entry != null ; entry = entry.next) {            if ((entry.hash == hash) && entry.key.equals(key)) {                V old = entry.value;                entry.value = value;                return old;            }        }        addEntry(hash, key, value, index);        return null;    }

我们可以看到好多synchronized,说明这个实现类,是线程安全的。
value不能为null,否则会报NullPointerException。

由一下代码Entry<?,?> tab[] = table;        int hash = key.hashCode();        int index = (hash & 0x7FFFFFFF) % tab.length;Entry<K,V> entry = (Entry<K,V>)tab[index];可以看出hashTable其存储方式和hashMap一样,也是无序的。

LinkedHashMap

1.非线程安全;
2.有序;双联表构成,(看源码没看懂,jdk1.8)
后续继续!

参考资料:
http://www.jianshu.com/p/9a48bcbdfece