Java Collections Framework source code analysis (5.1 - Map, TreeMap, red-black tree)

Java Collections Framework source code analysis (5.1 - Map, TreeMap, red-black tree)

MapDesign-related knowledge in Java Collections Framework in more data structures, whether at work or interviews will be frequently involved. By learning Mapthe source code, we were able to in-depth knowledge and understanding of data structures, a considerable part of the coding skills. In the next few articles will introduce some knowledge of data structures, I hope you will not be bored, because this part of the capacity is used as core competencies programmer. At the same time knowledge of this part is actually not so profound, I'll try to help you with the most straightforward way to understand.

Map Interface

MapCharacteristics of the data structure is clear, it allows us to use key store and read elements, and does not allow duplicate key. Different Mapimplementations for sequential processing key is inconsistent. For example, HashMapwe can not guarantee the order of the key, and TreeMapthe key is implemented in accordance with Comparatorthe interface method to determine the order.

MapOn each also defines a corresponding key-value data must implement Entrythe interface, the method defined above is also very simple, basically the operation for the key and value.

MapThe method defined on the interface, we should all be more familiar with, I'm not here long-winded. In particular I will mention several methods JDK8 added, more practical in their daily work. If you do not JDK8 experience before, you can find out.

* `getOrDefalut(Object key, V defaultValue)`:当 `Map` 中有 key 对应的 value 时返回 `Map` 中的 value, 否则返回 `defaultValue` 。
* `V compute(K key,BiFunction<? super K, ? super V, ? extends V> remappingFunction)`:将 `Map` 中的 key 和对应的 value 作为参数,调用 `remappingFunction` 方法获得 newValue,如果 newValue 不为 null,则替换原来的 value。
* `V putIfAbsent(K key, V value)`:如果当前 `Map` 中没有 key 对应的 value,则执行 put 操作。
* `V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)`:如果当前没有 key 对应的 value,则将参数 value 放入 `Map` 中,否则将原来 key 对应的 value 和新的 value 作为参数调用 `remappingFunction` ,将结果 put 入 `Map` 中。
复制代码

Implementation of these methods in Mapthe interface, JDK8 new use of defaultkeywords in order to maintain backward compatibility, specific code is very simple, there is not a long-winded.

TreeMap

Comparatively HashMap, the TreeMapknowledge involved in some less suitable as familiar with the Mapdata structure of the stepping stone. Let's look at it a class diagram:

We can see TreeMapinherits AbstractMapand implements the NavigableMapinterface. AbstractMapThe method provides a part of the template for developers to implement their own Map, and NavigableMapprovide the previously mentioned analogous NavigableSetto those methods, you can return a range of key or value. So we head straight to TreeMapthe specific implementation details.

Known from the beginning of a comment, TreeMapis achieved by the red-black tree data structure, it is possible to ensure containsKey, get, put, removethe time complexity is log(n). And the same, TreeMapis not thread-safe. So really understand TreeMapthe key is to understand and grasp the red-black tree data structure. So the next part, I will spend some length to help you brush up on red-black tree properties, do not think this is a very difficult task, I guarantee that after you read the series of articles will be able to red-black tree with Java handwriting.

Balanced binary tree

One sentence red-black tree is a balanced binary tree . The concept of a binary tree we should all know that each parent has no more than two child nodes of the tree. The balance means that the height of the left and right subtrees differ by no more than one. At the same time the value of all the left subtree of nodes smaller than the current, and the value of the child node of the tree to the right than the current large. Let's look at a few examples.

Can see in Figure 1 is a balanced binary tree, in line with the conditions we mentioned before, but not in compliance with Figure 2, because the left and right subtrees differ by more than the height of a.

Balanced binary tree

Non-balanced binary tree

The purpose is not to maintain a balanced binary tree degenerates into a linked list, so that you can perform binary search to find the time to keep the complexity log(n). But it also means an increase in node or nodes removed when the need to do a special operation to maintain the balance of the entire binary tree, which is such a red-black tree data structure.

Red-black tree

As before mentioned, the red-black tree is a balanced binary tree itself, so it has all the characteristics of a balanced binary tree. On this basis, it has some constraints with their own unique characteristics.

Each additional node red-black tree adds a characteristic color, ie red, or black, only one of these two in, which is also the origin of its name in red-black tree. We look at the TreeMapsource of the red-black tree node:

static final class Entry<K,V> implements Map.Entry<K,V> {
    K key;
    V value;
    Entry<K,V> left;
    Entry<K,V> right;
    Entry<K,V> parent;
    boolean color = BLACK;
}
复制代码

TreeMapEach node implements Mapthe Entry interfaces, in addition to left and right child nodes under the node representing the current key, value two data items, as well as the code itself nodes leftand right, as well as their parent node parent. The last is to represent the color of the current node color, where the same definitions in TreeMapthe source code:

private static final boolean RED   = false;
private static final boolean BLACK = true;
复制代码

Then we look at the characteristics of the red-black tree:

* 根节点(root node) 的颜色始终为黑色
* 两个相邻的节点(即连接在一起的节点)不能同为红色
* 从根节点出发,到某个子节点的每条路径上的黑色节点数量都相同
复制代码

how about it? Simple enough! Then let's look at an example.

From the above chart of view before we meet the three characteristics listed, make sure you verify the correct understanding of the concept of red-black tree.

The basic operation of the three red-black tree

Through the above description you should have mastered the concept of red-black tree, you know what is a red-black tree. Before the introduction of the red-black tree insert and delete operations, we first learn three basic operations that change color (color flip), left rotation (left rotation) and right rotation (right rotation).

Color changes

Very simple, the current node color to red, the color of the left and right child nodes are changed to black. Into the FIG.

Left and right rotation

There may be some words to describe the abstract, we look at the example picture, the picture from wikipedia.

Please Duokanjibian this picture, make sure you understand the left rotates clockwise and counterclockwise sense, because these three basic operation is the basis for the subsequent red-black tree insert and delete operations.

Epilogue

The main introduced Mapand TreeMapsome basic functions, and TreeMapthe basic concepts underlying red-black tree. Red-black tree is a more important level data structures for developers should be familiar with, and this introduces the basic concepts and operations base. And insert the specific algorithm Next we will be involved in the red-black tree delete operations, before entering this part, I again emphasize familiarize yourself with the contents of this article, because it is the basis of this foundation.

In the next article I will control TreeMapthe red-black tree algorithm source code introduction, I hope you do not miss!

I welcome attention to the micro-signal "and the lily of the people" for more high quality articles

Guess you like

Origin juejin.im/post/5e6ae265518825491949814f