HashMap集合

Map集合

    特點:以鍵值對方式存儲,key不可重複 value可重複

    常見實現類 HashMap   

    HashMap的底層主要是基於數組和鏈表來實現的,它之所以有相當快的查詢速度主要是因爲它是通過計算散列碼來來決定存儲的位置.

     HashMap中主要是通過key的hashCode來計算hash值的,只要hashCode相同,計算出來的hash值就一樣。如果存儲的對象對多了,就有可能不同的對象所算出來的hash值是相同的,這就出現了所謂的hash衝突。學過數據結構的同學都知道,解決hash衝突的方法有很多,HashMap底層是通過鏈表來解決hash衝突的。

public class HashMap<K,V>    
        extends AbstractMap<K,V>
        implements Map<K,V>, Cloneable, Serializable{
        transient Entry[] table;//元素爲內部類的對象的數組
        
        
    public V put(K key, V value) {
	    //當key爲null時,調用putForNullKey方法,將value放置在數組第一個位置。
      if (key == null)
      return putForNullKey(value);
      int hash = hash(key.hashCode());//根據 key 的 keyCode 計算 Hash 值
      int i = indexFor(hash, table.length);//搜索指定hash值在對應table中的索引
      for (Entry<K,V> e = table[i]; e != null; e = e.next) {//循環Entry
         Object k;
    	  //根據hash值或者key判斷相等
           if (e.hash==hash && ((k=e.key)==key||key.equals(k))) {
             V oldValue = e.value;
             e.value = value;//覆蓋舊值
             e.recordAccess(this);
             return oldValue;//方法返回舊的value值
         }
      }
      modCount++;//修改次數累加
      addEntry(hash, key, value, i);
      return null;
    }
              
        
     //內部類:維護鏈表的內容
     //實現了Map接口中Entry接口中的方法
    static class Entry<K,V> implements Map.Entry<K,V> {  
       final K key;//保存key
       V value;    //保存value
       Entry<K,V> next;//指向下一個節點
       final int hash; //保存hash值
        
     }

map集合的遍歷

方法一:

 public void get(Map<String, String> map) {
        Collection<String> c = map.values();
        Iterator it = c.iterator();
        for (; it.hasNext();) {
            System.out.println(it.next());
        }
    }

方法二:

public void getByKeySet(Map<String, String> map) {
        Set<String> key = map.keySet();
        for (Iterator it = key.iterator(); it.hasNext();) {
            String s = (String) it.next();
            System.out.println(map.get(s));
        }
    }

方法三:

public void getByEntry(Map<String, String> map) {
  Set<Map.Entry<String, String>> set = map.entrySet();
  for(Iterator<Map.Entry<String, String>> it = set.iterator(); it.hasNext();){
    Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
      System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }
}

 

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