Map---SortedMap-NavigableMap-TreeMap

SortedMap

概述

A {@link Map} that further provides a <em>total ordering</em> on its keys.
The map is ordered according to the {@linkplain Comparable natural ordering} of its keys, or by a {@link Comparator} typically provided at sorted map creation time.
This order is reflected when iterating over the sorted map's collection views (returned by the {@code entrySet}, {@code keySet} and {@code values} methods).
Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of {@link SortedSet}.)

SortedMap提供key排序

SortedMap使用 元素key的Comparable自然排序 或 创建时的Comparator;

使用SortedMap的entrySet、keySet、values会返回已排序的内容;

 

All keys inserted into a sorted map must implement the {@code Comparable} interface (or be accepted by the specified comparator).
Furthermore, all such keys must be <em>mutually comparable</em>: {@code k1.compareTo(k2)} (or {@code comparator.compare(k1, k2)}) must not throw a {@code ClassCastException} for any keys {@code k1} and {@code k2} in the sorted map.
Attempts to violate this restriction will cause the offending method or constructor invocation to throw a {@code ClassCastException}.

所有的key必须实现Comparable接口 或 指定comparator;

所有的key必须是可比较的;

 

public interface SortedMap<K,V> extends Map<K,V> {
        
    }

  

NavigableMap

概述

A {@link SortedMap} extended with navigation methods returning the closest matches for given search targets.
Methods {@code lowerEntry}, {@code floorEntry}, {@code ceilingEntry}, and {@code higherEntry} return {@code Map.Entry} objects associated with keys respectively less than, less than or equal, greater than or equal, and greater than a given key, returning {@code null} if there is no such key.

NavigableMap对SortedMap做了扩展:返回接近搜索目标的内容

lowerEntry、floorEntry、ceilingEntry、higherEntry返回 比key<、<=、>=、>的Map.Entry对象;

Similarly, methods {@code lowerKey}, {@code floorKey}, {@code ceilingKey}, and {@code higherKey} return only the associated keys.
All of these methods are designed for locating, not traversing entries.

lowerKey、floorKey、ceilingKey、higherKey返回关联的key;

所有的这些方法被设计用来定位查找

 

A {@code NavigableMap} may be accessed and traversed in either ascending or descending key order.
The {@code descendingMap} method returns a view of the map with the senses of all relational and directional methods inverted.
The performance of ascending operations and views is likely to be faster than that of descending ones.

NavigableMap可以按key的 升序/降序 访问

descendingMap方法返回一个降序的view;

升序的操作效率高于降序操作;

 

This interface additionally defines methods {@code firstEntry}, {@code pollFirstEntry}, {@code lastEntry}, and {@code pollLastEntry} that return and/or remove the least and greatest mappings, if any exist, else returning {@code null}.

NavigableMap定义了firstEntry、pollFirstEntry、lastEntry、pollLastEntry;

 

public interface NavigableMap<K,V> extends SortedMap<K,V> {
        
    }

  

TreeMap

概述

  

 

A Red-Black tree based {@link NavigableMap} implementation.
The map is sorted according to the {@linkplain Comparable natural ordering} of its keys, or by a {@link Comparator} provided at map creation time, depending on which constructor is used.

TreeMap是基于NavigableMap的 红黑树实现;

TreeMap使用 元素key的Comparable自然排序 或 创建时指定的Comparator;

 

This implementation provides guaranteed log(n) time cost for the {@code containsKey}, {@code get}, {@code put} and {@code remove} operations. 

containsKey、get、Put、remove操作 花费log(n)时间复杂度

 

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be <em>consistent with {@code equals}</em> if this sorted map is to correctly implement the {@code Map} interface. 

如果实现map接口,TreeMap的比较必须与equals一致;

This is so because the {@code Map} interface is defined in terms of the {@code equals} operation, but a sorted map performs all key comparisons using its {@code compareTo} (or {@code compare}) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. 

因为map使用equals比较,TreeMap使用Compare/CompareTo比较;

 

Note that this implementation is not synchronized.
If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it <em>must</em> be synchronized externally.

TreeMap的实现是线程非同步的;

如果多个线程并发进行结构修改TreeMap,必须在外部做同步;

(A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) 

结构修改指 add、delete或其他操作;仅改变key的value不是结构修改;

If no such object exists, the map should be "wrapped" using the {@link Collections#synchronizedSortedMap Collections.synchronizedSortedMap} method.  

可以使用Collections.synchronizedSortedMap;

 

The iterators returned by the {@code iterator} method of the collections returned by all of this class's "collection view methods" are <em>fail-fast</em>: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own {@code remove} method,

the iterator will throw a {@link ConcurrentModificationException}. 

TreeMap的iterator方法是fail-fast:如果iterator时操作remove(除了iterator的remove),将会抛出ConcurrentModificationException;

 

All {@code Map.Entry} pairs returned by methods in this class and its views represent snapshots of mappings at the time they were produced.
They do <strong>not</strong> support the {@code Entry.setValue} method.
(Note however that it is possible to change mappings in the associated map using {@code put}.)

方法返回的Map.Entry都是快照;

不支持Entry.setValue

(可以通过TreeMap的Put修改内容)

时间复杂度

Put:O(log(n))

remove:O(log(n))

get:O(log(n))

containsKey:O(log(n))

链路

treeMap.keySet().iterator();

// java.util.TreeMap.keySet
    public Set<K> keySet() {
        return navigableKeySet();
    }

    // java.util.TreeMap.navigableKeySet
    public NavigableSet<K> navigableKeySet() {
        TreeMap.KeySet<K> nks = navigableKeySet;
        return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
    }

    // java.util.TreeMap.KeySet
    static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {

    }

    // java.util.TreeMap.KeySet.iterator
    public Iterator<E> iterator() {
        if (m instanceof TreeMap)
            return ((TreeMap<E,?>)m).keyIterator();
        else
            return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
    }

    // java.util.TreeMap.keyIterator
    Iterator<K> keyIterator() {
        return new KeyIterator(getFirstEntry());
    }

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

    // java.util.TreeMap.PrivateEntryIterator
    abstract class PrivateEntryIterator<T> implements Iterator<T> {
        public final boolean hasNext() {
            return next != null;
        }

        final TreeMap.Entry<K,V> nextEntry() {
            TreeMap.Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            next = successor(e);
            lastReturned = e;
            return e;
        }

        public void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            // deleted entries are replaced by their successors
            if (lastReturned.left != null && lastReturned.right != null)
                next = lastReturned;
            deleteEntry(lastReturned);
            expectedModCount = modCount;
            lastReturned = null;
        }
    }

  

treeMap.values().iterator();

// java.util.TreeMap.values
    public Collection<V> values() {
        Collection<V> vs = values;
        if (vs == null) {
            vs = new Values();
            values = vs;
        }
        return vs;
    }
    
    // java.util.TreeMap.Values
    class Values extends AbstractCollection<V> {
        
    }
    
    // java.util.TreeMap.Values.iterator
    class Values extends AbstractCollection<V> {
        public Iterator<V> iterator() {
            return new ValueIterator(getFirstEntry());
        }
    }
    
    // java.util.TreeMap.ValueIterator
    final class ValueIterator extends PrivateEntryIterator<V> {
        public V next() {
            return nextEntry().value;
        }
    }

    // java.util.TreeMap.PrivateEntryIterator
    abstract class PrivateEntryIterator<T> implements Iterator<T> {
        public final boolean hasNext() {
            return next != null;
        }

        final TreeMap.Entry<K,V> nextEntry() {
            TreeMap.Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            next = successor(e);
            lastReturned = e;
            return e;
        }

        public void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            // deleted entries are replaced by their successors
            if (lastReturned.left != null && lastReturned.right != null)
                next = lastReturned;
            deleteEntry(lastReturned);
            expectedModCount = modCount;
            lastReturned = null;
        }
    }

  

 

treeMap.entrySet().iterator();

// java.util.TreeMap.entrySet
    public Set<Map.Entry<K,V>> entrySet() {
        EntrySet es = entrySet;
        return (es != null) ? es : (entrySet = new EntrySet());
    }
    
    // java.util.TreeMap.EntrySet
    class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        
    }
    
    // java.util.TreeMap.EntrySet.iterator
    class EntrySet extends AbstractSet<Map.Entry<K,V>> {
        public Iterator<Map.Entry<K,V>> iterator() {
            return new EntryIterator(getFirstEntry());
        }
    }
    
    // java.util.TreeMap.EntryIterator
    final class EntryIterator extends PrivateEntryIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() {
            return nextEntry();
        }
    }

    // java.util.TreeMap.PrivateEntryIterator
    abstract class PrivateEntryIterator<T> implements Iterator<T> {
        public final boolean hasNext() {
            return next != null;
        }

        final TreeMap.Entry<K,V> nextEntry() {
            TreeMap.Entry<K,V> e = next;
            if (e == null)
                throw new NoSuchElementException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            next = successor(e);
            lastReturned = e;
            return e;
        }

        public void remove() {
            if (lastReturned == null)
                throw new IllegalStateException();
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            // deleted entries are replaced by their successors
            if (lastReturned.left != null && lastReturned.right != null)
                next = lastReturned;
            deleteEntry(lastReturned);
            expectedModCount = modCount;
            lastReturned = null;
        }
    }

  

posted on 2023-11-08 16:19  anpeiyong  阅读(16)  评论(0编辑  收藏  举报

导航