Java set comparison ---- Map, java set ---- Map
Another big interface of a java set is Map. The biggest difference with Collection is that Collection stores an object, while Map stores a pair of objects, that is, key-Value storage, keys cannot be repeated. There are four classes that can instantiate Map: HashMap, Hashtable, WeakHashMap, and TreeMap.
Map traversal is to first obtain his set through entrySet (). Similarly, keySet () obtains the set of his key, and values () obtains the set of his value, then, use the set to retrieve the Iterator for traversal.
HashMap
It has all the features of Map. Both key and value can be null. It is not thread-safe. If the key is repeated, the value of the next key will overwrite the value of the previous key. The key will not be repeated in the saved set. He has an initial capacity (16) and a load factor (0.75 by default), and he has a threshold (initial capacity * load factor). If the size exceeds this threshold, the capacity is x 2.
Hashtable
It seems that he is similar to HashMap. The initial size of Hashtable is 11, and the size increases by x2 + 1 each time. Neither key nor value can be null, and Its thread is secure. The traversal sequence is inverse to the HashMap. The HashMap is backward, and the Hashtable is forward from the back. He has an additional Traversal method, Enumeration.
TreeMap
It seems that he is a key-value set with ordered keys. His key cannot be null or value. It is not thread-safe either.
WeakHashMap
He is similar to HashMap, but his key is weak and will be recycled by GC.
Finally, if you want to make the thread unsafe set safe, use the Collections. synchronizedMap, Collections. synchronizedSet, Collections. synchronizedList function as a solution.