HashMap,HashTable,HashSet區別

Hashtable是Dictionary的子類數組

HashMap是Map接口的一個實現類安全

HashTable的應用很是普遍,HashMap是新框架中用來代替HashTable的類,也就是說建議使用HashMap,不要使用HashTable。多線程

區別:框架

1.HashTable的方法是同步的,HashMap未經同步,因此在多線程場合要手動同步HashMap這個區別就像Vector和ArrayList同樣。spa

2.HashTable不容許null值(key和value都不能夠),HashMap容許null值(key和value均可以)。HashMap容許key值只能由一個null值,由於hashmap若是key值相同,新的key, value將替代久的。線程

3.HashTable有一個contains(Object value),功能和containsValue(Object value)功能同樣。對象

4.HashTable使用Enumeration,HashMap使用Iterator。接口

以上只是表面的不一樣,它們的實現也有很大的不一樣。get

5.HashTable中hash數組默認大小是11,增長的方式是 old*2+1。HashMap中hash數組的默認大小是16,並且必定是2的指數。同步

6.哈希值的使用不一樣,HashTable直接使用對象的hashCode

以上只是一些比較突出的區別,固然他們的實現上仍是有不少不一樣的,好比

HashMap對null的操做。

HashMap能夠看做三個視圖:key的Set,value的Collection,Entry的Set。這裏HashSet就是其實就是HashMap的一個視圖。HashSet內部就是使用Hashmap實現的,和Hashmap不一樣的是它不須要Key和Value兩個值。

HashMap爲散列映射,它是基於hash table的一個實現,它可在常量時間內安插元素,或找出一組key-value pair.HashSet爲散列集,它把查找時間看的很重要,其中全部元素必需要有hashCode()

HashtableHashMap的區別:

  1.Hashtable是Dictionary的子類,HashMap是Map接口的一個實現類;

  2.Hashtable中的方法是同步的,而HashMap中的方法在缺省狀況下是非同步的。便是說,在多線程應用程序中,不用專門的操做就安全地可使用Hashtable了;而對於HashMap,則須要額外的同步機制。但HashMap的同步問題可經過Collections的一個靜態方法獲得解決:

  Map Collections.synchronizedMap(Map m)

  這個方法返回一個同步的Map,這個Map封裝了底層的HashMap的全部方法,使得底層的HashMap即便是在多線程的環境中也是安全的。

  3.在HashMap中,null能夠做爲鍵,這樣的鍵只有一個;能夠有一個或多個鍵所對應的值爲null。當get()方法返回null值時,便可以表示HashMap中沒有該鍵,也能夠表示該鍵所對應的值爲null。所以,在HashMap中不能由get()方法來判斷HashMap中是否存在某個鍵,而應該用containsKey()方法來判斷。



public static void main(String[] args) {

  Hashtable<Integer, String> table = new Hashtable<Integer, String>();

  table.put(1, "1");

  //table.put(2, null);   //Hashtable 不容許null值 有null就會報異常

  

for(int i=0;i<table.size();i++){

   System.out.println(table.get(1));

  }

  System.out.println("#############");

  HashMap<Integer, String> map = new HashMap<Integer, String>();

  map.put(1, "2");

  map.put(2, "3");

  map.put(null,null);      //HashMap 容許null值,但key只能有一個null,不然後面不會被保存,

  for(int i=0;i<map.size();i++){

   System.out.println(map.get(1));

  }

  

  System.out.println("#############");

//HashSet  值不能重複  無序的不能用get()來取對象

  HashSet<Integer> s = new HashSet<Integer>();

  s.add(Integer.valueOf(1));

  s.add(Integer.valueOf(1));

  for(Integer i:s){

   System.out.println(i);

  }

 }

相關文章
相關標籤/搜索