JAva集合-HashMap(JDK 1.8)

42372 ワード

一、基本概念
HashMapはハッシュテーブルのMapインタフェースの実装に基づいている.このインプリメンテーションでは、オプションのマッピング操作がすべて提供され、null値とnullキーを使用できます.以前はJDKでHashMapはビットバケツ+チェーンテーブル方式、すなわち我々がよく言うハッシュチェーンテーブル方式を採用していたが、JDK 1.8ではビットバケツ+チェーンテーブル/赤黒木方式を採用しており、非スレッドで安全であった.あるバケツのチェーンテーブルの長さがバルブ値に達すると、このチェーンテーブルは赤と黒の木に変換されます.注意事項:
  • HashMapは、キー値ペア(key-value)マッピングを格納するハッシュ・リストである.
  • HashMapはAbstractMapに継承され、Map、Cloneable、java.io.Serializableインタフェースを実現した.
  • HashMapの実装は同期ではなく、スレッドが安全ではないことを意味します.そのkey、valueはnullであってもよい.
  • HashMapにおけるマッピングは秩序化されていない.
  • HashMapの例には、初期容量とロードファクタの2つのパラメータがあります.

  • 二、ソース分析
    1:定数
       /** map      */
        static final int MAXIMUM_CAPACITY = 1 << 30;
    
        /** *        */
        static final float DEFAULT_LOAD_FACTOR = 0.75f;
    
        /**  list         , list size      */
        static final int TREEIFY_THRESHOLD = 8;
    
        /** resize   ,    untreeify    */
        static final int UNTREEIFY_THRESHOLD = 6;
    
        /**        tree      */
        static final int MIN_TREEIFY_CAPACITY = 64;
    

    2:メインフィールド
    /**         */
     transient Node<K,V>[] table;
     /**   map     */
     transient Set<Map.Entry<K,V>> entrySet;
    
        /**      */
        transient int size;
    
        /**      */
        transient int modCount;
    
        /**   ,       */ int threshold; /**      */
        final float loadFactor;

    3:主なメソッドgetメソッド:
    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 && //                
                    ((k = first.key) == key || (key != null && key.equals(k))))
                    return first;
                if ((e = first.next) != null) {
                //      TreeNode,   TreeNode.getTreeNode()           
                    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;
        }

    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)
            //table  ,n table   
                n = (tab = resize()).length;
                //i    ,    
            if ((p = tab[i = (n - 1) & hash]) == null)
                tab[i] = newNode(hash, key, value, null);
            else {
            //  i        ,        Node p        key hash key  
                Node<K,V> e; K k;
                if (p.hash == hash &&
                    ((k = p.key) == key || (key != null && key.equals(k))))
                    //  key     
                    e = p;
                else if (p instanceof TreeNode)
                //    ,   p   TreeNode,      
                    e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
                else {
                // i         p.next null   ,binCount          ,                 ,         tree    ,       tree。
                    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;
        }

    resize()は、競合を解決する方法がlistであるか、赤黒数であるかのいずれかであるため、resize()は複雑な点である.
    /** * Initializes or doubles table size. If null, allocates in * accord with initial capacity target held in field threshold. * Otherwise, because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move * with a power of two offset in the new table. * * @return the table */
        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; //    2  
            }
            else if (oldThr > 0) // initial capacity was placed in threshold
                newCap = oldThr;
            else {               // zero initial threshold signifies using defaults
                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;
            @SuppressWarnings({"rawtypes","unchecked"})
            //      newCap newTab,  oldTab  Node    ,         tree    。
                Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
            table = newTab;
            if (oldTab != null) {
                for (int j = 0; j < oldCap; ++j) {
                    Node<K,V> e;
                    if ((e = oldTab[j]) != null) {
                        oldTab[j] = null;
                        if (e.next == null)
                            newTab[e.hash & (newCap - 1)] = e;
                        else if (e instanceof TreeNode)
                        // split        lower  upper tree   ,           UNTREEIFY_THRESHOLD  ,   untreeify,       newTab 。
                            ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                        else { // preserve order
                            Node<K,V> loHead = null, loTail = null;
                            Node<K,V> hiHead = null, hiTail = null;
                            Node<K,V> next;
                            do {
                                next = e.next;
                                if ((e.hash & oldCap) == 0) {
                                    if (loTail == null)
                                        loHead = e;
                                    else
                                        loTail.next = e;
                                    loTail = e;
                                }
                                else {
                                    if (hiTail == null)
                                        hiHead = e;
                                    else
                                        hiTail.next = e;
                                    hiTail = e;
                                }
                            } while ((e = next) != null);
                            if (loTail != null) {
                                loTail.next = null;
                                newTab[j] = loHead;
                            }
                            if (hiTail != null) {
                                hiTail.next = null;
                                newTab[j + oldCap] = hiHead;
                            }
                        }
                    }
                }
            }
            return newTab;
        }
    

    remove()メソッド
    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) > 0 &&
                (p = tab[index = (n - 1) & hash]) != null) {
                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;
                    //           getTreeNode       
                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;
                }
            }
            return null;
        }

    HashMapインスタンス
    1:Hashmapの遍歴方法
    package com.csu.collection;
    
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map.Entry;
    import java.util.Set;
    
    public class HashMapTest {
    
        public static void main(String[]args)
        {
            HashMap<Integer, Integer> map=new HashMap<>();
            for(int i=0;i<10000000;i++)
            {
                map.put(i, i);
            }
            System.out.println("       :for each map.entrySet()");
            long startTime1=System.currentTimeMillis();
            for(Entry<Integer, Integer> entry:map.entrySet())
            {
                entry.getValue();
                entry.getKey();
            }
            long endTime1=System.currentTimeMillis();
            System.out.println("         :"+(endTime1-startTime1)+"ms");
            System.out.println(" 2     :map.entrySet()      ");
            long startTime2=System.currentTimeMillis();
            Iterator<Entry<Integer, Integer>> iterator=map.entrySet().iterator();
            while(iterator.hasNext())
            {
                HashMap.Entry<Integer, Integer> entry=(Entry<Integer, Integer>) iterator.next();
                entry.getValue();
                entry.getKey();
            }
            long endTime2=System.currentTimeMillis();
            System.out.println(" 2       :"+(endTime2-startTime2)+"ms");
            System.out.println(" 3     : for each map.keySet(),   get  ");
            long startTime3=System.currentTimeMillis();
            for (Integer key : map.keySet()) {
                map.get(key);
            }
            long endTime3=System.currentTimeMillis();
            System.out.println(" 3       :"+(endTime3-startTime3)+"ms");
            System.out.println(" 4     :for each map.entrySet(),       map.entrySet()");
            long startTime4=System.currentTimeMillis();
            Set<Entry<Integer, Integer>> entrySet = map.entrySet();
            for (Entry<Integer, Integer> entry : entrySet) {
                entry.getKey();
                entry.getValue();
            }
            long endTime4=System.currentTimeMillis();
            System.out.println(" 4       :"+(endTime4-startTime4)+"ms");
        }
    }
    

    実行結果
    for each map.entrySet()
             :71ms
     2map.entrySet()      
     283ms
     3for each map.keySet(),   get  
     3117ms
     4for each map.entrySet(),       map.entrySet()
     484ms

    まとめ:
  • a.HashMapのループは、keyもvalueも必要であれば、for each map.entrySet()を直接使用する.
  • valueを必要とせずにkeyを巡回するだけであれば、for each map.keySet()を直接使用してget取得を呼び出すことができます.2:Hashmapによるキャッシュ
  • public class Student {
        private String name;
        private String address;
        public Student(String name,String address)
        {
            this.address=address;
            this.name=name;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
    }
    
    import java.io.Serializable;
    
    public class CacheEntity implements Serializable {
    
        /** * */
        private static final long serialVersionUID = 1L;
    
        private final int DEFUALT_TIME=200;// 
    
        private String  key;
        private Object value;
        private int time;//      ,         
        private long timeoutStamp;//        
    
        @SuppressWarnings("unused")
        private CacheEntity()
        {
            this.timeoutStamp=System.currentTimeMillis()+DEFUALT_TIME*1000;
            this.time=DEFUALT_TIME;
        }
        public CacheEntity(String key,Object value)
        {
            this.key=key;
            this.value=value;
        }
        public CacheEntity(String key,Object value,long timestamp)
        {
            this(key,value);
            this.timeoutStamp=timestamp;
        }
        public CacheEntity(String key,Object value,int time)
        {
            this(key,value);
            this.time=time;
            this.timeoutStamp=System.currentTimeMillis()+DEFUALT_TIME*1000;
        }
        public String getKey() {
            return key;
        }
        public void setKey(String key) {
            this.key = key;
        }
        public Object getValue() {
            return value;
        }
        public void setValue(Object value) {
            this.value = value;
        }
        public int getTime() {
            return time;
        }
        public void setTime(int time) {
            this.time = time;
        }
        public long getTimeoutStamp() {
            return timeoutStamp;
        }
        public void setTimeoutStamp(long timeoutStamp) {
            this.timeoutStamp = timeoutStamp;
        }
    }
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    /** * *     ,           * */
    public class CacheByHashMap {
    
    
        private static  HashMap<String, CacheEntity> map;
        private static List<CacheEntity> tempList;
        static{
            tempList=new ArrayList<CacheEntity>();
            map=new HashMap<String,CacheEntity>(1<<10); 
            new Thread(new RemoveTimeOutCacheThread()).start();
    
        }
      /** *      * @param key * @param value * @param time */
        public static synchronized void addCache(String key,CacheEntity value,int time)
        {
            value.setTimeoutStamp(System.currentTimeMillis()+time*1000);
            map.put(key, value);
            tempList.add(value);
        }
        /** *        * @param key * @return */
        public static synchronized CacheEntity getCache(String key)
        {
            return map.get(key);
        }
        /** *          key * @param key * @return */
        public static synchronized boolean isContainsKey(String key)
        {
            return map.containsKey(key);
        }
        /** *      * @param key */
        public static synchronized void removeCache(String key)
        {
            map.remove(key);
        }
        /** *        * @return */
        public static int getCacheSize()
        {
          return  map.size();
        }
        /** *        */
        public static synchronized void clearCache()
        {
            tempList.clear();
            map.clear();
            System.out.println("       ");
        }
        static class RemoveTimeOutCacheThread implements Runnable{
    
            @Override
            public void run() {
                // TODO Auto-generated method stub
                while(true)
                {
                    try {
                        checkTime();
                    } catch (Exception e) {
                        // TODO: handle exception
                        e.printStackTrace();
                    }
                }
            }
    
            private void checkTime() throws InterruptedException
            {
                CacheEntity value=null;
                long timeoutTime=1000l;
                if(tempList.size()<1)
                {
                    System.out.println("      !");
                    timeoutTime=1000l;
                    Thread.sleep(timeoutTime);
                    return ;
                }
                value=tempList.get(0);
                timeoutTime=value.getTimeoutStamp()-System.currentTimeMillis();
                if(timeoutTime>0)
                {
                    Thread.sleep(timeoutTime);
                    return ;
                }
                System.out.println("      "+value.getKey());
                tempList.remove(value);
                removeCache(value.getKey());
            }
    
        }
    
    }
    

    テストエンドコード:
    public class CacheTest {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Student student1=new Student("zhangsan", "shangsha");
            Student student2=new Student("wangqiang", "beijing");
            Student student3=new Student("zhangsi", "shanghai");
            Student student4=new Student("zhangwu", "wuhan");
            Student student5=new Student("zhangqi", "zhengzhou");
            Student student6=new Student("zhangba", "shangsha");
            CacheEntity cacheEntity1=new CacheEntity("1", student1, 30);
            CacheEntity cacheEntity2=new CacheEntity("2", student2, 30);
            CacheEntity cacheEntity3=new CacheEntity("3", student3, 30);
            CacheEntity cacheEntity4=new CacheEntity("4", student4, 30);
            CacheEntity cacheEntity5=new CacheEntity("5", student5, 30);
            CacheEntity cacheEntity6=new CacheEntity("6", student6, 30);
            //    
            CacheByHashMap.addCache(cacheEntity1.getKey(), cacheEntity1, cacheEntity1.getTime());
            CacheByHashMap.addCache(cacheEntity2.getKey(), cacheEntity2, cacheEntity2.getTime());
            CacheByHashMap.addCache(cacheEntity3.getKey(), cacheEntity3, cacheEntity3.getTime());
            CacheByHashMap.addCache(cacheEntity4.getKey(), cacheEntity4, cacheEntity4.getTime());
            CacheByHashMap.addCache(cacheEntity5.getKey(), cacheEntity5, cacheEntity5.getTime());
            CacheByHashMap.addCache(cacheEntity6.getKey(), cacheEntity6, cacheEntity6.getTime());
            if(CacheByHashMap.isContainsKey("2"))
            {
                System.out.println("        ");
                //          get()
            }
            else {
                CacheByHashMap.addCache(cacheEntity2.getKey(), cacheEntity2, cacheEntity2.getTime());
                //              ,     
            }
    
        }
    }
    

    実行結果:
           
          1
          2
          3
          4
          5
          6
          !
          !