天天看點

Java集合:HashMap使用詳解及源碼分析

1 使用方法

  HashMap是散清單,存儲的内容為key-value鍵值對,key的值是唯一的,可以為null。

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {}
           

  HashMap繼承了AbstractMap并實作了Map、Cloneable以及Serializable接口,是以HashMap支援clone和序列化。

1.1 方法介紹

  HashMap提供的API主要如下:

void                 clear() //清空HashMap
Object               clone() //複制HashMap
boolean              containsKey(Object key) //判斷是否存在key
boolean              containsValue(Object value) //判斷是否存在Value
Set<Entry<K, V>>     entrySet() //傳回HashMap的Entry組成的set集合
V                    get(Object key) //擷取鍵為key的元素值
boolean              isEmpty() //判空
Set<K>               keySet() //擷取HashMap的key組成的set集合
V                    put(K key, V value) //加入HashMap
void                 putAll(Map<? extends K, ? extends V> map) //批量加入
V                    remove(Object key) //删除鍵為key的Entry
int                  size() //擷取大小
Collection<V>        values() //擷取HashMap的value集合
           

1.2 使用示例

public void testHashMap() {
    //建立hashMap
    HashMap hashMap = new HashMap(); //建立hashMap
    //添加元素
    hashMap.put(, "one");
    hashMap.put(, "two");
    hashMap.put(, "three");
    hashMap.put(, "four");
    //列印元素
    this.printMapByEntrySet(hashMap);
    //擷取大小
    System.out.println("hashMap的大小為: " + hashMap.size());
    //是否包含key為4的元素
    System.out.println("hashMap是否包含key為4的元素: " + hashMap.containsKey());
    //是否包含值為5的元素
    System.out.println("hashMap是否包含value為two的元素: " + hashMap.containsValue("two"));

    hashMap.put(, "five");
    hashMap.put(, "six");

    //删除元素
    System.out.println("删除key為2的元素: " + hashMap.remove());
    //列印元素
    this.printMapByKeySet(hashMap);
    //clone
    HashMap cloneMap = (HashMap) hashMap.clone();
    //列印克隆map
    System.out.println("cloneMap的元素為: " + cloneMap);
    //清空map
    hashMap.clear();
    //判空
    System.out.println("hashMap是否為空: " + hashMap.isEmpty());
}

/**
 * 根據entrySet()擷取Entry集合,然後周遊Set集合擷取鍵值對
 * @param map
 */
private void printMapByEntrySet(HashMap map) {
    Integer key = null;
    String value = null;
    Iterator iterator = map.entrySet().iterator(); //
    System.out.print("hashMap中含有的元素有: ");
    while (iterator.hasNext()) {
        Map.Entry entry = (Map.Entry) iterator.next();
        key = (Integer) entry.getKey();
        value = (String) entry.getValue();
        System.out.print("key/value : " + key + "/" + value + " ");
    }
    System.out.println();
}

/**
 * 使用keySet擷取key的Set集合,利用key擷取值
 * @param map
 */
private void printMapByKeySet(HashMap map) {
    Integer key = null;
    String value = null;
    Iterator iterator = map.keySet().iterator();
    System.out.print("hashMap中含有的元素有: ");
    while (iterator.hasNext()) {
        key = (Integer) iterator.next();
        value = (String) map.get(key);
        System.out.print("key/value : " + key + "/" + value + " ");
    }
    System.out.println();
}
           

  運作結果如下:

hashMap中含有的元素有: key/value : /one key/value : /two key/value : /three key/value : /four
hashMap的大小為: 
hashMap是否包含key為的元素: true
hashMap是否包含value為two的元素: true
删除key為的元素: two
hashMap中含有的元素有: key/value : /one key/value : /three key/value : /four key/value : /five key/value : /six
cloneMap的元素為: {=one, =three, =four, =five, =six}
hashMap是否為空: true
           

2 源碼分析

2.1構造函數

  HashMap有四個構造函數,每個構造函數的不同之處在于初始容量和加載因子不同。初始容量為申請的HashMap初始大小,當加入元素後的容量大于加載因子和目前容量的乘積是,HashMap需要再hash增大容量。

/**
 * 申請初始容量為initialCapacity, 加載因子為loadFactor
 * @param initialCapacity 初始容量
 * @param loadFactor 加載因子
 * @throws IllegalArgumentException 非法參數異常
 */
public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < )
        throw new IllegalArgumentException("Illegal initial capacity: " +
                initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY) //最大容量為2^30
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <=  || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " +
                loadFactor);
    this.loadFactor = loadFactor; //加載因子
    this.threshold = tableSizeFor(initialCapacity); //容量大小, >=initialCapacity的最小的2的倍數
}

/**
 * 初始容量大小為initialCapacity, 加載因子為預設0.75
 * @param  initialCapacity the initial capacity.
 * @throws IllegalArgumentException if the initial capacity is negative.
 */
public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

/**
 * 初始容量大小為0, 加載因子為0.75
 */
public HashMap() {
    this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}

/**
 * 申請一個HashMap并且用m初始化
 *
 * @param   m the map whose mappings are to be placed in this map
 * @throws  NullPointerException if the specified map is null
 */
public HashMap(Map<? extends K, ? extends V> m) {
    this.loadFactor = DEFAULT_LOAD_FACTOR;
    putMapEntries(m, false);
}
           

2.2 put方法

/**
 * 為HashMap插入一個鍵為key,值為value的元素
 * @param key
 * @param value
 * @return
 */
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) == ) //hash數組為null或者長度為0
        n = (tab = resize()).length; //初始化數組
    if ((p = tab[i = (n - ) & 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) //TreeNode節點
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = ; ; ++binCount) {
                if ((e = p.next) == null) { //将元素節點連結到最後
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - ) // -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;
}
           

2.3 get方法

/**
 * 擷取鍵為key的鍵值對的值
 * @param key
 * @return
 */
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) >  &&
            (first = tab[(n - ) & 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;
}
 remove方法
/**
 * 删除鍵為key的鍵值對
 * @param key
 * @return
 */
public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
}

/**
 * Implements Map.remove and related methods
 *
 * @param hash hash for key
 * @param key the key
 * @param value the value to match if matchValue, else ignored
 * @param matchValue if true only remove if value is equal
 * @param movable if false do not move other nodes while removing
 * @return the node, or null if none
 */
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K, V>[] tab;
    Node<K, V> p;
    int n, index;
    if ((tab = table) != null && (n = tab.length) >  &&
            (p = tab[index = (n - ) & hash]) != null) { //hash表不為空,長度 > 0,下标對應的元素存在
        Node<K, V> node = null, e;
        K k;
        V v;
        if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k)))) //判斷第一個元素
            node = p;
        else if ((e = p.next) != null) { //同一下标有多個元素,周遊連結清單
            if (p instanceof TreeNode)
                node = ((TreeNode<K, V>) p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                            ((k = e.key) == key ||
                                    (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                (value != null && value.equals(v)))) { //删除元素
            if (node instanceof TreeNode)
                ((TreeNode<K, V>) node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
}
           

3 HashMap和Hashtable差別

  HashMap和Hashtable從功能上來說幾乎完全相同,主要差別在于Hashtable是線程安全的而HashMap不是。

  1)HashMap的key和Value可以接受null,Hashtable不行;

  2)Hashtable除了構造函數外幾乎所有的方法都加上了synchronized保證線程安全,HashMap沒有線程安全保證;

  3) Hashtable由于使用了synchronized導緻在單線程情況下速度較慢;

  4) Hashtable構造時預設大小為11,HashMap為16;

參考:

[1] http://www.cnblogs.com/skywang12345/p/3310835.html

[2] http://blog.csdn.net/mazhimazh/article/details/17876641

[3] http://blog.csdn.net/ns_code/article/details/36034955