Java-集合篇-HashMap

Map接口:
數據結構:哈希表
哈希表:通過關鍵碼來映射到值的一個數據結構
哈希函數:鍵與值映射的一個映射關係

哈希函數:
1.直接尋址法 : f(x)=kx+b (k、b都是常數)
2.除留餘數法 : f(x)=x%k (k<=m)[m爲存儲位置長度]

哈希衝突:m!=n 但是 f(m)=f(n)
解決:1.鏈地址法
   2.探測法(線性探測、隨機探測)

HashMap:

常用方法:
int size(); map中存儲鍵值對的個數
boolean isEmpty(); 判斷集合是否爲空
boolean containsKey(Object key); 判斷鍵是否存在
boolean containsValue(Object value); 判斷值是否存在
void putAll(Map<? extnds K, ? extends V> m);
void clear();清除集合

HashMap JDK源碼分析:

繼承關係

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

繼承了AbstractMap(jdk1.2)、實現了map接口implements Map<K,V>,可以克隆、可以序列化

構造函數

//指定初始容量、指定加載因子
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();
}

   //通過默認加載因子和默認容量初始化
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public HashMap() {
        this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
    }

   //通過map集合來初始化當前集合
    public HashMap(Map<? extends K, ? extends V> m) {
        this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
                      DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
        inflateTable(threshold);

        putAllForCreate(m);
    } 

put方法添加元素

public V put(K key, V value) {
     //第一次插入元素,需要對數組進行初始化:注意:數組大小爲2的指數關係
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    //可以存儲key爲null的情況
    if (key == null)
        return putForNullKey(value);
    //key不爲null 
    //通過key來哈希找到該數據所存在的索引位置:key相關的哈希值   
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    //遍歷該位置i下面的鏈表:(判斷key是否存在,存在替換value,不存在創建新entry)
    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;
} 

插入key爲null情況:
key爲null做特殊處理,存儲在table索引位0號位置
遍歷該位置下的鏈表,查看key爲null的節點是否存在,存在即將value更新爲傳入的value
若該鏈表下不存在則創建新的entry節點插入該鏈表

private V putForNullKey(V value) {
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    modCount++;
    addEntry(0, null, value, 0);
    return null;
} 

擴容方式

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; // double threshold
        }
        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"})
            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)
                        ((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;
    }

默認值
private static final long serialVersionUID = 362498820763181265L;
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
哈希表中數組默認初始值大小爲16
static final int MAXIMUM_CAPACITY = 1 << 30;
哈希表中數組最大容量值
static final float DEFAULT_LOAD_FACTOR = 0.75f;
默認的加載因子-》擴容使用
static final int TREEIFY_THRESHOLD = 8;
static final int UNTREEIFY_THRESHOLD = 6;
static final int MIN_TREEIFY_CAPACITY = 64;

HashMap底層的實現是數組+鏈表實現:數組中存儲的是一個個entry實體,hash到同一個索引位置的數據通過鏈表鏈接起來

使用迭代器遍歷HashMap:

public static void main(String[] args) {
        HashMap <String, String> hashMap = new HashMap <String, String>();

        //插入元素 put
        hashMap.put("zhangsan", "1");
        hashMap.put("lisi","2");
        hashMap.put("wangwu","3");
        hashMap.put("lilei",null);
        hashMap.put(null,"1");
        //通過鍵獲取值得方法
//        String lisi = hashMap.get("2");
//        System.out.println(hashMap.size());
        //刪除元素
//        hashMap.remove(null);

//        System.out.println(hashMap.size());
//        System.out.println(lisi);
//        System.out.println(hashMap.containsKey("lilei"));
//        System.out.println(hashMap.size());

        /**
         * 數據無序
         * 鍵不能重複、值可以重複
         * 鍵和值都能爲null
         */


        //對map集合的遍歷:3種遍歷方式
        //通過鍵值對遍歷
        //先將HashMap實例轉化爲set實例(類型map.entry<>)
        Iterator <Map.Entry <String, String>> iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry <String, String> next = iterator.next();
            String key = next.getKey();
            String value = next.getValue();
            System.out.print(key+":"+value+" ");
        }
        System.out.println();
        //通過鍵來遍歷
        //僅僅對鍵進行訪問
        Iterator <String> iterator1 = hashMap.keySet().iterator();
        while (iterator1.hasNext()) {
            String next = iterator1.next();
            System.out.print(next+" ");
        }

        System.out.println();
        //通過值來對map集合進行遍歷
        Iterator <String> iterator2 = hashMap.values().iterator();
        while (iterator2.hasNext()) {
            String next = iterator2.next();
            System.out.print(next+" ");
        }
    }

HashMap的簡單應用:
產生100000個隨機數(範圍爲1-1000),統計各個數字出現的次數

 public static void main(String[] args) {
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        Random random = new Random();
        for(int i =0 ;i<100000 ;i++){
            int value = random.nextInt(1000)+1;
            Integer v = hashMap.get(value);
            if(v==null) {
                hashMap.put(value, 1);
            }else {
                v++;
                hashMap.put(value,v);
            }
        }
        Iterator<Map.Entry<Integer,Integer>> iterator = hashMap.entrySet().iterator();
        int count = 0;
        while(iterator.hasNext()){
            count++;
            Map.Entry<Integer,Integer> next = iterator.next();
            Integer key = next.getKey();
            Integer value = next.getValue();
            System.out.print(key+":"+value+"   ");
            if(count==20){
                System.out.println();
                count = 0;
            }
        }
        System.out.println();

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章