Java中HashMap与HashTable的区别

来源:互联网 发布:大数据教程 pdf 编辑:程序博客网 时间:2024/06/11 15:54

原文地址:Differences between HashMap and HashTable in Java

HashMap与HashTable在哈希表中存储键值对。当用HashTable或者HashMap的时候,我们指定一个对象用作key,还有一个指向这个key的value。然后对这个key进行hash操作,得到的哈希码用于在表中存放value的索引。

Java代码样例

// A sample Java program to demonstrate HashMap and HashTableimport java.util.*;import java.lang.*;import java.io.*;/* Name of the class has to be "Main" only if the class is public. */class Ideone{    public static void main(String args[])    {        //----------hashtable -------------------------        Hashtable<Integer,String> ht=new Hashtable<Integer,String>();        ht.put(101," ajay");        ht.put(101,"Vijay");        ht.put(102,"Ravi");        ht.put(103,"Rahul");        System.out.println("-------------Hash table--------------");        for (Map.Entry m:ht.entrySet()) {            System.out.println(m.getKey()+" "+m.getValue());        }        //----------------hashmap--------------------------------        HashMap<Integer,String> hm=new HashMap<Integer,String>();        hm.put(100,"Amit");        hm.put(104,"Amit");  // hash map allows duplicate values        hm.put(101,"Vijay");        hm.put(102,"Rahul");        System.out.println("-----------Hash map-----------");        for (Map.Entry m:hm.entrySet()) {            System.out.println(m.getKey()+" "+m.getValue());        }    }}

输出:

-------------Hash table--------------103 Rahul102 Ravi101 Vijay-----------Hash map-----------100 Amit101 Vijay102 Rahul104 Amit

HashMap vs HashTable

  1. HashMap不是同步的。它不是线程安全的,所以在没有恰当的synchronization代码的情况下多线程之间不能共享。然而HashTable是同步的,它是线程安全的,可以被多线程共享。
  2. HashMap允许NULL key,多个NULL value。HashTable是不允许有null key和value的。
  3. HashMap一般优于HashTable,如果同步不是必须的话。

为什么HashTable不允许有null而HashMap允许有?

为了能够成功地从HashTable中存储并检索,用作key的对象必须实现hashCode方法还有equals方法。因为null不是一个对象,所以不能实现这些方法。HashMap是HashTable的一个改进版本。HashMap是后面创造出来的。

来源:

Sources:
http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html:
http://qa.geeksforgeeks.org/558/differences-between-hashmap-hashtable-and-hashset-in-java?show=558#q558

0 0
原创粉丝点击