📜  Java哈希表和同步映射的区别

📅  最后修改于: 2021-09-12 11:00:23             🧑  作者: Mango

Hashtable 类实现了一个哈希表,它将键映射到值。任何非空对象都可以用作键或值。要成功地从 Hashtable 存储和检索对象,用作键的对象必须实现 hashCode 方法和 equals 方法。

哈希表的特点:

  • 它有点像 HashMap 但是是同步的。
  • Hashtable 将键/值对存储在哈希表中。
  • 在 Hashtable 中,我们指定了一个用作键的对象,以及我们希望与该键关联的值。然后对键进行散列,所得散列代码用作将值存储在表中的索引。
  • Hashtable 类的初始默认容量为 11,而负载因子为 0.75。
  • HashMap 不提供任何枚举,而 Hashtable 提供非快速失败的枚举。

例子:

Java
// Java program to demonstrate the
// usage of HashTable
  
import java.util.*;
class Hashtable1 {
    public static void main(String args[])
    {
        // Creating a HashTable
        Hashtable mytable = new Hashtable();
  
        // Adding elements to HashTable
        mytable.put(1, "James Bond");
        mytable.put(2, "Donald Trumph");
        mytable.put(3, "Joe Biden");
        mytable.put(4, "Mona Lisa");
  
        // Iterating through HashTable
        for (Map.Entry m : mytable.entrySet()) 
        {
            System.out.println(m.getKey() + " "
                               + m.getValue());
        }
    }
}


Java
// Java program to demonstrate the
// usage of Synchronized HashMap
  
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapSyncExample {
    public static void main(String args[])
    {
        // Creating HashMap
        HashMap hmap = new HashMap();
        
        // Adding elements in HashMap
        hmap.put(2, "Anil");
        hmap.put(44, "Ajit");
        hmap.put(1, "Brad");
        hmap.put(4, "Sachin");
        hmap.put(88, "XYZ");
  
        Map map = Collections.synchronizedMap(hmap);
        Set set = map.entrySet();
        
        synchronized (map)
        {
            Iterator i = set.iterator();
            
            // Display elements
            while (i.hasNext())
            {
                Map.Entry me = (Map.Entry)i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            }
        }
    }
}


输出
4 Mona Lisa
3 Joe Biden
2 Donald Trumph
1 James Bond

同步哈希映射

  • 对象级别的同步。
  • 每个读/写操作都需要获取锁。
  • 锁定整个集合是一种性能开销。
  • 这基本上只允许一个线程访问整个地图并阻止所有其他线程。
  • 它可能会引起争用。
  • SynchronizedHashMap 返回迭代器,它在并发修改时快速失败。

例子:

Java

// Java program to demonstrate the
// usage of Synchronized HashMap
  
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class HashMapSyncExample {
    public static void main(String args[])
    {
        // Creating HashMap
        HashMap hmap = new HashMap();
        
        // Adding elements in HashMap
        hmap.put(2, "Anil");
        hmap.put(44, "Ajit");
        hmap.put(1, "Brad");
        hmap.put(4, "Sachin");
        hmap.put(88, "XYZ");
  
        Map map = Collections.synchronizedMap(hmap);
        Set set = map.entrySet();
        
        synchronized (map)
        {
            Iterator i = set.iterator();
            
            // Display elements
            while (i.hasNext())
            {
                Map.Entry me = (Map.Entry)i.next();
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            }
        }
    }
}
输出
1: Brad
2: Anil
4: Sachin
88: XYZ
44: Ajit

Hashtable 与 SynchronizedHashMap

                               Hashtable                                                                                         Synchronized HashMap                                         

Hashtable doesn’t allow even a single null key and null values.

Synchronized HashMap allows one null key and any number of null values.

Iterators returned by Hashtable are fail-safe in nature. i.e they don’t throw ConcurrentModificationException if the map is modified after the creation of the iterator.

Iterators returned by synchronized HashMap are fail-fast in nature. i.e they throw ConcurrentModificationException if the map is modified after the creation of iterator.

HashTable was there since JDK 1.1. From JDK 1.2, it has been made a part of Java Collection Framework.

HashMap is introduced in JDK 1.2.

HashTable is the legacy class. It is sometimes considered as due for deprecation. So, it is recommended that not to use HashTable in your applications.

If you want a high level of data consistency, then only consider using synchronized HashMap.