📜  Java中HashMap和HashTable的区别

📅  最后修改于: 2022-05-13 01:54:38.211000             🧑  作者: Mango

Java中HashMap和HashTable的区别

HashMap 和 Hashtable 将键值对存储在哈希表中。使用 Hashtable 或 HashMap 时,我们指定一个用作键的对象以及要链接到该键的值。然后对键进行哈希处理,生成的哈希码用作值存储在表中的索引。现在让我们借助一个例子来讨论。

哈希图与哈希表

  • HashMap 是非同步的。它不是线程安全的,如果没有适当的同步代码,就不能在多个线程之间共享,而 Hashtable 是同步的。它是线程安全的,可以与许多线程共享。
  • HashMap 允许一个空键和多个空值,而 Hashtable 不允许任何空键或空值。
  • 如果不需要线程同步,HashMap 通常优于 HashTable。

Hashmap 和 Hashtable 的区别

S. No.HashmapHashtable
1.No method is synchronized.Every method is synchronized.
2.Multiple threads can operate simultaneously and hence hashmap’s object is not thread-safe.At a time only one thread is allowed to operate the Hashtable’s object. Hence it is thread-safe.
3.Threads are not required to wait and hence relatively performance is high.It increases the waiting time of the thread and hence performance is low.
4.Null is allowed for both key and value.Null is not allowed for both key and value. Otherwise, we will get a null pointer exception.
5.It is introduced in the 1.2 version.It is introduced in the 1.0 version.
6. It is non-legacy.It is a legacy.

现在你一定想知道为什么 HashTable 不允许 null 而 HashMap呢?

答案很简单。为了成功地从 HashTable 存储和检索对象,用作键的对象必须实现 hashCode 方法和 equals 方法。由于 null 不是对象,因此无法实现这些方法。 HashMap 是 Hashtable 的高级版本和改进。 HashMap 是后来创建的。

例子:

Java
// Java program to demonstrate
// HashMap and HashTable
import 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 ht=new Hashtable();
        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 hm=new HashMap();
        hm.put(100,"Amit");
        hm.put(104,"Amit"); 
        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 Rahul
102 Ravi
101 Vijay
-----------Hash map-----------
100 Amit
101 Vijay
102 Rahul
104 Amit