Java TreeMap source code parsing

Source: Internet
Author: User

Java TreeMap source code parsing

Following the introduction of HashMap in the previous article, this article introduces another important class TreeMap in the Map series. You may feel that there are many articles about HashMap on the Internet, but there are not so many articles about TreeMap. The reason is: on the one hand, there are many HashMap application scenarios; second, compared with HashMap, TreeMap uses more complex data structures. If you don't talk nonsense, go to the topic.

Signature)

Public class TreeMap <K, V>
Extends AbstractMap <K, V>
Implements NavigableMap <K, V>, Cloneable, java. io. Serializable

As you can see, compared with HashMap, TreeMap inherits an interface NavigableMap, which determines the differences between TreeMap and HashMap:

The key of HashMap is unordered, and the key of TreeMap is ordered.

Interface NavigableMap

First, let's take a look at the NavigableMap signature.

Public interface NavigableMap <K, V> extends SortedMap <K, V>

It is found that NavigableMap inherits SortedMap, and then looks at the SortedMap signature.

SortedMap

Public interface SortedMap <K, V> extends Map <K, V>

SortedMapJust like its name indicates that the Map is ordered. This sequence is generally determined by the natural order natural ordering of the keys provided by the Comparable interface. Alternatively, you can specify a Comparator when creating a SortedMap instance. When we use collection views from a set perspective, like HashMap, which is also provided by the entrySet, keySet, and values methods) to iterate A SortedMap instance, the order of keys is displayed. For the differences between Comparable and Comparator, see here ):

  • Comparable generally indicates the natural order of classes. For example, if you define a Student class, the Student ID is sorted by default.

  • Comparator generally indicates the special category of a class in a certain situation and requires customized sorting. For example, you want to sort data by the age of the Student class.

All the class classes that insert the key in SortedMap must inherit the Comparable class or specify a comparator) to determine how to comparek1.compareTo(k2)Orcomparator.compare(k1, k2)) Two keys. Otherwise, an error is reported during insertion.ClassCastException. This is, the order of keys in SortedMap should beequalsThe methods are consistent. That is to sayk1.compareTo(k2)Orcomparator.compare(k1, k2)If it is true,k1.equals(k2)It should also be true. After introducing SortedMap, return to our NavigableMap. NavigableMap is added to JDK1.6. Based on SortedMap, it adds some "navigation methods" navigation methods) to return and search for the elements closest to the target. For example, the following methods:

  • LowerEntry returns all elements smaller than the given Map. Entry.

  • FloorEntry returns all elements smaller or equal to the given Map. Entry.

  • CeilingEntry, returns all elements larger or equal to the given Map. Entry.

  • HigherEntry returns all elements larger than the given Map. Entry.

Design concept)

Red-black tree)

TreeMap is implemented based on the red and black trees. The red and black trees are a binary search tree. Let's recall some of the properties of the binary search tree together.

Binary Search Tree

First look at binary search tree, BST) What is it like?

Binary Search Tree

I believe everyone is familiar with this image. The key point is:

The value of the Left subtree is smaller than the root node, and the value of the right subtree is greater than the root node.

The advantage of the Binary Search Tree is that the problem can be halved every time you make a decision. Therefore, if the binary search tree is balanced, the time complexity of searching elements islog(n)That is, the height of the tree. I think of a serious question here. If the Binary Search Tree reduces the number of problems by half, then the triple search tree will not reduce the number of problems by 2/3. This is not better, and so on, we can also have a four-way search tree, a five-way search tree ...... For more general cases:

Which of the n elements is the best efficiency for K-tree search? K = 2?

K-cross search tree

According to my analysis above, you may also fall into a misunderstanding:

When the three-way search tree reduces the problem scale by 2/3, the number of comparison operations required is that the two-way search tree reduces the problem scale by half, only one comparison operation is required)

We cannot ignore these two attempts. For more general cases:

The average number of comparisons required for the K-tree search tree isk*log(n/k).

In extreme cases, when k = n, the K-tree is converted to a linear table, and the complexity isO(n)If you use a mathematical perspective to solve this problem, it is equivalent:

When n is a fixed value and k is used,k*log(n/k)Minimum value?

k*log(n/k)The operation rule based on the logarithm can be convertedln(n)*k/ln(k),ln(n)Is a constant, so it is equivalentk/ln(k). This is a simple question for first-year students with high learning skills. Let's look at the results here.

When k is e,k/ln(k)Take the minimum value.

The value of natural number e is about 2.718. We can see that the binary tree is basically the optimal solution. Perform the following operations in REPL of Nodejs

 
  1. function foo(k) {return k/Math.log(k);} 
  2. > foo(2) 
  3. 2.8853900817779268 
  4. > foo(3) 
  5. 2.730717679880512 
  6. > foo(4) 
  7. 2.8853900817779268 
  8. > foo(5) 
  9. 3.1066746727980594 

It seems that k = 3 is smaller than k = 2. That is to say, the three-way search tree should be better than the two-way search tree, but why is the binary tree more popular? Later, I found the answer on the omnipotent stackoverflow. The theme is as follows:

The current CPU can be used to optimize the code of double logic binary logic. The Triple logic is divided into multiple double logic.

In this way, we can probably understand why binary trees are so popular, because we can reduce the number of problems by half at most during a comparison operation. Okay, it's a little far away. Let's go back to the red-black tree.

Red/black tree

First look at the red and black trees:

Red/black tree example

It is captured from the wiki. It must be noted that:

The leaf node is the NIL node. Some textbooks in China do not have this NIL node. We sometimes omit these NIL nodes when drawing a picture, but we need to make it clear that when we talk about leaf nodes, these NIL nodes.

The red and black trees use the following five rules to ensure that the trees are balanced:

After the preceding five conditions are met, the following conditions can be ensured:The maximum path from the root node to the leaf node is no more than twice the minimum path from the root node to the leaf node.. In fact, this is a good understanding, mainly using the nature of 4 and 5, here to put it simply:

Assuming that the number of black nodes is B in the shortest path from the root node to the leaf node, the number of black nodes is B in the longest path from the root node to the leaf node according to the Nature 5, the longest condition is that there is a red node in the middle of each two black nodes, that is, the red and black), so the red node is a maximum of B-1. This will prove the above conclusion.

Red/black tree operation

The NIL node is not drawn in the red/black tree rotation example)

I think it is best to visualize the insert, delete, left-hand, and right-hand operations of the red and black trees. The text expression is complicated and I will not be ugly here, you can also find more on the Internet, such as v_July_v's "teach you a thorough understanding of the red and black trees". I recommend a swf tutorial video in English. Do not be afraid of it, but focus on the image ??), About 7 minutes. There is also a visual web page of interactive red and black trees. You can perform operations on your own, insert several nodes, delete several nodes, and see how the left and right sides play.

Source code analysis

I will not talk about the operation of the red and black trees here, so there is basically no source code to talk about here, because the important algorithms here areFrom CLRThe CLR here refers to Cormen, Leiserson, and Rivest. They are the authors of the introduction to algorithms. That is to say, the algorithms in TreeMap are pseudo code referring to the introduction to algorithms. Because the red/black tree is a balanced binary search tree, its put contains the update operation.) the time complexity of get and remove islog(n).

Summary

So far, the implementation of TreeMap and HashMap has been fully introduced. We can see that their implementation is different, which determines their application scenarios:

  • The keys of TreeMap are ordered, and the time complexity of adding, deleting, modifying, and querying operations isO(log(n))To ensure the balance between the red and black trees, rotate as necessary.
  • The key of HashMap is unordered, and the time complexity of adding, deleting, modifying, and querying operations isO(1)In order to achieve dynamic resizing, resize is performed when necessary.

In addition, I have not explained the specific code here, and it is inevitable that some titles will join the party. Please forgive me for understanding it more deeply.

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.