1. 程式人生 > 其它 >Collections中的synchronizedMap(Map<K,V> m)方法

Collections中的synchronizedMap(Map<K,V> m)方法

技術標籤:Javajava

Java中Map有兩種:Hashtable、HashMap
Hashtable執行緒安全,HashMap執行緒不安全
synchronizedMap(Map<K,V> m)方法返回指定集合物件對應的同步物件。

如果引數是HashMap物件,有沒有可能返回一個執行緒安全的Hashtable物件?

從方法的返回值來看,該推測沒有邏輯上的錯誤。

  1. 我們首先通過程式碼進行測試:
public class test {
    /**
     * hashtable的key、value不能是null,否則空指標異常
     * hashMap執行緒不安全, hashtable執行緒安全
     * 但是以下程式碼驗證synchronizedMap方法並不是將hashMap轉換成hashtable
     * 因為轉換之仍然是可以對key、value賦值null
     */
public static void main(String[] args) { Map<String, String > map = new HashMap<>(); Map<String, String > table = new Hashtable<>(); map.put("001","LLL"); Collections.synchronizedMap(map); map.put(null, null); System.
out.println(map.keySet()); table.put(null, null); } }
[null, 001]
Exception in thread "main" java.lang.NullPointerException
	at java.util.Hashtable.put(Hashtable.java:460)
	at Note.Collection.Collections.test.main(test.java:19)

驗證失敗。

  1. 從類的屬性和繼承關係來看
public class Hashtable<K,V>
extends Dictionary<K,V> implements Map<K,V>, Cloneable, java.io.Serializable{ private transient Entry<?,?>[] table; private transient int count; private int threshold; private float loadFactor; }
public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
 
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    static final int TREEIFY_THRESHOLD = 8;
    static final int UNTREEIFY_THRESHOLD = 6;
    static final int MIN_TREEIFY_CAPACITY = 64;
    }

Hashtable和HashMap並非繼承關係,並且兩個類之間屬性方法差別巨大,無法發生轉型。

結論: HashMap並沒有轉型成為Hashtable。該方法只是給將該物件轉換成同步物件,並沒有對其型別改變。