What you overlooked about TreeMap

Things you don't know about TreeMap

What is TreeMap?

​ TreeMap, you can see from the name, it uses a tree structure to implement Map mapping, and its underlying implementation uses a red-black tree, which can be seen from part of the code of the official Java TreeMap (there is a color for the node ):

private void fixAfterDeletion(Entry<K,V> x)Method (used to restore the balance of the tree):

/** From CLR */
    private void fixAfterDeletion(Entry<K,V> x) {
    
    
        while (x != root && colorOf(x) == BLACK) {
    
    
            if (x == leftOf(parentOf(x))) {
    
    
                Entry<K,V> sib = rightOf(parentOf(x));

                if (colorOf(sib) == RED) {
    
    
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateLeft(parentOf(x));
                    sib = rightOf(parentOf(x));
                }

                if (colorOf(leftOf(sib))  == BLACK &&
                    colorOf(rightOf(sib)) == BLACK) {
    
    
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
    
    
                    if (colorOf(rightOf(sib)) == BLACK) {
    
    
                        setColor(leftOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateRight(sib);
                        sib = rightOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(rightOf(sib), BLACK);
                    rotateLeft(parentOf(x));
                    x = root;
                }
            } else {
    
     // symmetric
                Entry<K,V> sib = leftOf(parentOf(x));

                if (colorOf(sib) == RED) {
    
    
                    setColor(sib, BLACK);
                    setColor(parentOf(x), RED);
                    rotateRight(parentOf(x));
                    sib = leftOf(parentOf(x));
                }

                if (colorOf(rightOf(sib)) == BLACK &&
                    colorOf(leftOf(sib)) == BLACK) {
    
    
                    setColor(sib, RED);
                    x = parentOf(x);
                } else {
    
    
                    if (colorOf(leftOf(sib)) == BLACK) {
    
    
                        setColor(rightOf(sib), BLACK);
                        setColor(sib, RED);
                        rotateLeft(sib);
                        sib = leftOf(parentOf(x));
                    }
                    setColor(sib, colorOf(parentOf(x)));
                    setColor(parentOf(x), BLACK);
                    setColor(leftOf(sib), BLACK);
                    rotateRight(parentOf(x));
                    x = root;
                }
            }
        }

        setColor(x, BLACK);
    }

Do you know the purpose of TreeMap?

​ Before talking about its use, we must first talk about its nature, its nature is actually almost the same as the nature of the red-black tree, because it uses each node of the red-black tree to store one Entry(即一个键值对). In addition, We also know that the red-black tree is actually a balanced binary search tree. In this case, the nodes must be compared when inserting nodes. If they are the same, they will be covered. One time guarantee 红黑树上每一个节点存储的值都是不一样的. It is well known that the keys in the Map are all The only thing that is not repeated, so in summary, when the red-black tree compares nodes, it actually compares the Key of each Entry.

A little summary:

  • Realized by red-black tree, Key is not repeated and
  • Each Node on the red-black tree is an Entry (ie KV pair)
  • In order to ensure the balance of the red-black tree, it is necessary to ensure that the stored keys are comparable

Knowing the above knowledge, we try to think we know Setthe data structure, the value of which stores are also not repeated, it is part of nature and not above us when it comes to the TreeMap's a bit like it?

​ In fact, TreeSet in Java is implemented with TreeMap! Let's take a look at some of its source code:

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{
    
    
	private transient NavigableMap<E,Object> m;
	
	TreeSet(NavigableMap<E,Object> m) {
    
    
        this.m = m;
    }
    
    public TreeSet() {
    
    
        this(new TreeMap<E,Object>());
    }
    
    public TreeSet(Comparator<? super E> comparator) {
    
    
        this(new TreeMap<>(comparator));
    }
    
    //后面的代码省略....

}

​ Let's take a brief look. It can be seen from the construction method that when initializing a TreeSet, it is actually initializing one NavigableMap, and it is actually a TreeMap. In fact, TreeSet is implemented by storing values ​​in Key through TreeMap, and all Values ​​are null.

Why does HashMap even with TreeMap?

​ I believe that this problem is ignored by people, and almost not many people have thought about it carefully, because before exploring why, you need to have a certain understanding of red-black trees and hash tables, but this article wants to take you through reading This article explores this issue. Therefore, this article will first tell you the reason for the birth of HashMap and what are the limitations of TreeMap, and will start to explain HashMap. Okay, let’s just go straight to the topic!

  • Limitations of TreeMap

    When talking about the nature of TreeMap before, I mentioned K. 比较性This is actually the limitation of TreeMap, because many times the data we store is not comparable. Therefore, when storing, compare those The manipulation of is actually a waste of performance

  • Why do we need HashMap

    After knowing the limitations of TreeMap, you can probably guess why HashMap was born. In fact, HashMap is a kind of data that does not consider the comparability of Key, and compared to the O(log(n)) time complexity of TreeMap, it can reach O(1) level, and its bottom layer is 哈希表implemented by using

​ HashMap will be explained in detail in future articles

Guess you like

Origin blog.csdn.net/weixin_44829930/article/details/112062842