Java set comparison ---- Map, java set ---- Map

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.