java - TreeMap

java - TreeMap

 

 

Features

 

  • TreeMap is an ordered key-value collection, which is implemented by a red-black tree.
  • TreeMap inherits from AbstractMap and implements Map, Cloneable, and java.io.Serializable interfaces.
  • TreeMap implements the NavigableMap interface, which means that it supports a series of navigation methods. For example, return an ordered set of keys.
  • TreeMap is implemented based on a Red-Black tree. The map is sorted according to the natural ordering of its keys, or according to the Comparator provided when the map was created, depending on the constructor used.
  • TreeMap is not synchronized, so the iterator returned by its iterator method is fail-fastl.

 

 

Expansion

 

    Since TreeMap is based on a red-black tree, its fundamental implementation is a linked list, so the capacity is dynamically increased by one according to the addition of elements.

    TreeMap and TreeSet are the same.

 

 

 

Constructor of TreeMap

 

// Default constructor. Using this constructor, the elements in the TreeMap are arranged in natural ordering.
TreeMap()

// Created TreeMap contains Map
TreeMap(Map<? extends K, ? extends V> copyFrom)

// Specify the comparator for the Tree
TreeMap(Comparator<? super K> comparator)

// Created TreeSet contains copyFrom
TreeMap(SortedMap<K, ? extends V> copyFrom)

 

 

 

 

TreeMap API

 

Entry<K, V>                ceilingEntry(K key)
K                          ceilingKey(K key)
void                       clear()
Object                     clone()
Comparator<? super K>      comparator()
boolean                    containsKey(Object key)
NavigableSet<K>            descendingKeySet()
NavigableMap<K, V>         descendingMap()
Set<Entry<K, V>>           entrySet()
Entry<K, V>                firstEntry()
K                          firstKey()
Entry<K, V> floorEntry(K key)
KfloorKey(Kkey)
V                          get(Object key)
NavigableMap<K, V>         headMap(K to, boolean inclusive)
SortedMap<K, V>            headMap(K toExclusive)
Entry<K, V>                higherEntry(K key)
K                          higherKey(K key)
boolean                    isEmpty()
Set<K>                     keySet()
Entry<K, V>                lastEntry()
K                          lastKey()
Entry<K, V>                lowerEntry(K key)
K                          lowerKey(K key)
NavigableSet<K>            navigableKeySet()
Entry<K, V>                pollFirstEntry()
Entry<K, V>                pollLastEntry()
V                          put(K key, V value)
V                          remove(Object key)
int                        size()
SortedMap<K, V>            subMap(K fromInclusive, K toExclusive)
NavigableMap<K, V>         subMap(K from, boolean fromInclusive, K to, boolean toInclusive)
NavigableMap<K, V>         tailMap(K from, boolean inclusive)
SortedMap<K, V>            tailMap(K fromInclusive)

 

 

 

 

data structure

 

    The essence of TreeMap is RB Tree (red-black tree), which contains several important member variables: root, size, comparator.

 

  • root is the root node of the red-black tree. It is an Entry type. Entry is the node of the red-black tree. It contains 6 basic components of the red-black tree: key (key), value (value), left (left child), right (right child), parent ( parent node), color (color). Entry nodes are sorted by key, and the content contained in the Entry node is value. 
  • When the comparator red and black numbers are sorted, they are sorted according to the keys in the Entry; the comparison size of the keys in the Entry is judged according to the comparator comparator.
  • size is the number of nodes in the red and black numbers.

 

Introduction to red-black trees

 

      A red-black tree, also known as a red-black binary tree, is first of all a binary tree, which has all the characteristics of a binary tree. At the same time, the red-black tree is a self-balancing sorted binary tree.

 

      We know that for a basic binary tree, they all need to satisfy a basic property - that is, the value of any node in the tree is greater than its left child node and less than its right child node. According to this basic property, the retrieval efficiency of the tree is greatly improved. We know that the process of generating a binary tree is very easy to be out of balance, and the worst case is one-sided (only right/left subtrees), which will inevitably lead to a greatly reduced retrieval efficiency of the binary tree (O(n)), so in order to maintain the binary tree For balance, the big cows have proposed various algorithms, such as: AVL, SBT, spread tree, TREAP, red-black tree and so on.

 

      A balanced binary tree must have the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and both left and right subtrees are a balanced binary tree. That is to say, for any child node of the binary tree, the heights of its left and right subtrees are similar.



 

red-black tree features

 

  • Each node can only be red or black
  • root node is black
  • Each leaf node (NIL node, empty node) is black.
  • If a node is red, both of its children are black. That is to say, two adjacent red nodes cannot appear on a path.
  • All paths from any node to each of its leaves contain the same number of black nodes.

    To put it bluntly, the red-black tree is to make data search, insertion and deletion more efficient, and its retrieval efficiency is O(log n)

 

 

Red-Black Tree Learning Articles

 

Collection of red and black tree series

Red-black tree data structure analysis

red-black tree

 

 

 

 

性能问题

 

    在性能上,TreeMap由于要排序,所以插入和删除要比HashMap慢一点,但是如果key是自然顺序或自定义顺序,其实性能上会更好点。

 

 

 

TreeMap遍历方法

 

    TreeMap有顺序遍历和逆序遍历

 

顺序遍历

Iterator<K> keyIterator() {
    return new KeyIterator(getFirstEntry());
}

 

final class KeyIterator extends PrivateEntryIterator<K> {
    KeyIterator(Entry<K,V> first) {
        super(first);
    }
    public K next() {
        return nextEntry().key;
    }
}

 

 

逆序遍历

Iterator<K> descendingKeyIterator() {
    return new DescendingKeyIterator(getLastEntry());
}

 

final class DescendingKeyIterator extends PrivateEntryIterator<K> {
    DescendingKeyIterator(Entry<K,V> first) {
        super(first);
    }
    public K next() {
        return prevEntry().key;
    }
}

 

 

其它遍历一

// 假设map是TreeMap对象
// map中的key是String类型,value是Integer类型
Integer integ = null;
Iterator iter = map.entrySet().iterator();
while(iter.hasNext()) {
    Map.Entry entry = (Map.Entry)iter.next();
    // 获取key
    key = (String)entry.getKey();
        // 获取value
    integ = (Integer)entry.getValue();
}

 

 

其它遍历二

// 假设map是TreeMap对象
// map中的key是String类型,value是Integer类型
String key = null;
Integer integ = null;
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
        // 获取key
    key = (String)iter.next();
        // 根据key,获取value
    integ = (Integer)map.get(key);
}

 

 

其它遍历三

// 假设map是TreeMap对象
// map中的key是String类型,value是Integer类型
Integer value = null;
Collection c = map.values();
Iterator iter= c.iterator();
while (iter.hasNext()) {
    value = (Integer)iter.next();
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992907&siteId=291194637