java hash table, the corresponding tree container class. HashMap and how to resolve conflicts?

Hash tree corresponding container classes:

Hash table: hashmap, hashtable, concurrentHashmap
tree: hashset, treemap, treeset

which treeset inherited from the treemap, hashset inherited from hashmap

 

Performance Analysis:

Entry: key and value combinations. I.e., a map entry <K, V> .

treemap underlying the use of a " red-black tree " to save the collection of the Entry , which means TreeMap add elements, remove elements of performance than HashMap low. When TreeMap elements are added, by the need to find new cycle Entry insertion position, and therefore more consumption performance; when treemap when removed elements, to find the right order by traversing Entry , relatively consumption performance. But TreeMap , TreeSet than HashMap , HashSet that advantage: TreeMap all of Entry always press key to maintain an orderly state in accordance with the rules specified order, TreeSet all elements always remain orderly state based on the specified collation .

 

Causes and solutions of conflict:

HashMap call hashCode () method to calculate the hashCode . Because in Java are two different objects may have the same hashCode, so that different keys may have the same hashCode , it will lead to conflict.

bucket: the hash table array elements can be stored position is called " bucket ( bucket ) " , each bucket has its index is specified, the system can quickly access its index based on bucket element in the store.

Hashmap inside the bucket appeared in the form of a single linked list, hash table to solve a problem is the conflict in the hash value, typically two methods: Method list and open addressing method.

Method chain is the same hash object values organized into a list on the hash value of the corresponding slots;

Opening address method is through a detection algorithm, when the case of a slot has been occupied continue to find the next slot can be used.
Detection methods are: a linear law detection method detection level detection method randomly

 

In addition jdk7 and jdk8 in HashMap difference:

jdk7 in hashMap using arrays + list. If too many nodes in a hash collision occurs, if you want to find one of the nodes requires O (the n- ) lookup time.

jdk8 in hashMap using arrays + list / black trees, when the length of the list a bit bucket reaches a certain threshold, the list will be converted to red-black tree. Red-black tree time complexity of O (nlogn).

 

Published 62 original articles · won praise 34 · views 40000 +

Guess you like

Origin blog.csdn.net/qq_42451835/article/details/104220819