1. 程式人生 > >HashMap和HashTable的異同點

HashMap和HashTable的異同點

HashMap和HashTable異同點

底層資料: HashMap和HashTable底層資料結構相同,都是以陣列加連結串列形式儲存資料。

繼承關係: HashMap和HashTable都實現了Clonable ,Map,Serializable介面。 但不同的是HashTable繼承了Dictionary介面。
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable

public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable{}

增長方式: 擴容時機相同,都是在size大於擴容閾值(陣列容量×載入因子)的時候進行擴容。 但HashMap擴容方式是2table.length ,而HashTable是2table.length + 1。

內部方法 : HashTable的put方法,remove方法都有關鍵字sychronized修飾(確保安全性)。

Key-Value鍵值對:HashMap中的key不能重複,key和value都可以為null。 而HashTable的key和value都不能為null。

遍歷方式:HashMap可以通過迭代器進行遍歷。 而HashTable有特有的列舉方法進行遍歷。

Key—Value為null情況

:HashMap的put方法: HashMap遇到key為null的時候,呼叫putForNullKey方法進行處理,而對value沒有處理;Hashtable遇到null,直接返回NullPointerException。

安全性: HasMap執行緒不安全,Hashtable執行緒安全(因為有關鍵字Sychronized修飾)

其他
HashMap 和 hashtable= (同時處理(put)10W,100W,40000W資料) ,比較快慢?

  HashMap<Integer,Integer> hashMap = new HashMap<>();
  long b = System.currentTimeMillis();
  for(int i=0; i<NUM; i++) {
        hashMap.put((int) (Math.random()*10),(int) (Math.random()*10));
  }
  long e = System.currentTimeMillis();
  System.out.println("hashmap time : " + (e-b));
    
  Hashtable<Integer,Integer> hashtable = new Hashtable<>();
  long b1 = System.currentTimeMillis();
  for(int i=0; i<NUM; i++) {
        hashtable.put((int) (Math.random()*10),(int) (Math.random()*10));
  }
  long e1 = System.currentTimeMillis();
  System.out.println("hashtable time : " + (e1-b1));

結果::HashMap 比 hashtable 快。

原因(hashtable:sychronized修飾,java程式和作業系統相互切換 (使用者端和核心相互切換)) 而HashMap只在使用者端操作,不用切換。 (在單執行緒下 資料不多的情況用HashMap。)
sychronized關鍵字是一個重量級鎖(只能有一個執行緒對其進行操作),涉及使用者空間和核心空間的切換 ;