TreeMap源码详解

本文深入解析了SortedMap和NavigableMap接口,重点介绍了TreeMap类,包括其基于红黑树的实现、构造方法、核心方法如size、containsKey、getEntry等,以及特有的导航和排序功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、继承关系图

在这里插入图片描述

二、SortedMap接口介绍

进一步提供其键的总排序的Map 。 映射根据其键的自然顺序进行排序,或者由通常在排序映射创建时提供的Comparator进行排序。

1、方法介绍

Comparator<? super K> comparator();

返回一个比较器对象, 根据此比较器进行比较。

SortedMap<K,V> subMap(K fromKey, K toKey);

返回两个key之间的Map视图。

SortedMap<K,V> headMap(K toKey);

返回键小于toKey的Map视图。

SortedMap<K,V> tailMap(K fromKey);

返回键大于等于fromKey的视图。

K firstKey();

返回最小键。

K lastKey();

返回最大键。

Set<K> keySet();

迭代器按升序返回键集合的视图。

Collection<V> values();

值集合。

Set<Map.Entry<K, V>> entrySet();

映射集合。

三、NavigableMap接口介绍

这个接口扩展了SortedMap接口,添加了返回与小于、小于或等于、大于或等于和大于给定键的键关联的Map.Entry对象。

1、方法介绍

Map.Entry<K,V> lowerEntry(K key);

返回与严格小于给定键的最大键关联的键值映射,如果没有这样的键,则返回null 。

K lowerKey(K key);

返回严格小于给定键的最大键,如果没有这样的键,则返回null 。

Map.Entry<K,V> floorEntry(K key);

返回与小于或等于给定键的最大键关联的键值映射,如果没有这样的键,则返回null 。

K floorKey(K key);

返回小于或等于给定键的最大键,如果没有这样的键,则返回null 。

Map.Entry<K,V> ceilingEntry(K key);

返回与大于或等于给定键的最小键关联的键值映射,如果没有这样的键,则返回null 。

K ceilingKey(K key);

返回大于或等于给定键的最小键,如果没有这样的键,则返回null 。

Map.Entry<K,V> higherEntry(K key);

返回与严格大于给定键的最小键关联的键值映射,如果没有这样的键,则返回null 。

K higherKey(K key);

返回严格大于给定键的最小键,如果没有这样的键,则返回null 。

Map.Entry<K,V> firstEntry();

返回最小键值对。

Map.Entry<K,V> lastEntry();

返回最大键值对。

Map.Entry<K,V> pollFirstEntry();

删除并返回最小键值对。

Map.Entry<K,V> pollLastEntry();

删除并返回最大键值对。

NavigableMap<K,V> descendingMap();

返回可导航的逆序视图。

NavigableSet<K> navigableKeySet();

返回可导航的键集合。

NavigableSet<K> descendingKeySet();

返回可导航的逆序的键集合。

NavigableMap<K,V> subMap(K fromKey, boolean fromInclusive,
                         K toKey,   boolean toInclusive);

子视图。

NavigableMap<K,V> headMap(K toKey, boolean inclusive);

返回此映射部分的视图,其键小于(或等于,如果inclusive为真) toKey 。

NavigableMap<K,V> tailMap(K fromKey, boolean inclusive);

同上。

四、TreeMap类介绍

基于红黑树的NavigableMap实现。 映射根据其键的自然顺序进行排序,或者通过映射创建时提供的Comparator排序,具体取决于使用的构造函数。

1、属性介绍

// 比较器
private final Comparator<? super K> comparator;

// 根节点
private transient Entry<K,V> root;

// 元素个数
private transient int size = 0;

// 修改变量
private transient int modCount = 0;

// 各种视图
private transient EntrySet entrySet;
private transient KeySet<K> navigableKeySet;
private transient NavigableMap<K,V> descendingMap;

2、构造方法

public TreeMap() {
    comparator = null;
}

public TreeMap(Comparator<? super K> comparator) {
    this.comparator = comparator;
}

public TreeMap(Map<? extends K, ? extends V> m) {
    comparator = null;
    putAll(m);
}

public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}

这里比较特殊的就是参数为集合的两个构造方法,我们分别来看一下。

public void putAll(Map<? extends K, ? extends V> map) {
	// 给size赋值
    int mapSize = map.size();
    // 这里首先判断映射是不是有序的
    if (size==0 && mapSize!=0 && map instanceof SortedMap) {
    	// 获取有序映射的比较器
        Comparator<?> c = ((SortedMap<?,?>)map).comparator();
        // 这里的判断一般是false,因为c = null
        if (c == comparator || (c != null && c.equals(comparator))) {
            ++modCount;
            try {
                buildFromSorted(mapSize, map.entrySet().iterator(),
                                null, null);
            } catch (java.io.IOException cannotHappen) {
            } catch (ClassNotFoundException cannotHappen) {
            }
            return;
        }
    }
    super.putAll(map);
}

public void putAll(Map<? extends K, ? extends V> m) {
    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
        put(e.getKey(), e.getValue());
}

// 这里它重写了put方法
public V put(K key, V value) {
    Entry<K,V> t = root;
    // 如果根为空就把它当作根
    if (t == null) {
        compare(key, key); // type (and possibly null) check

        root = new Entry<>(key, value, null);
        size = 1;
        modCount++;
        return null;
    }
    int cmp;
    Entry<K,V> parent;
    // split comparator and comparable paths
    Comparator<? super K> cpr = comparator;
    // 若比较器不为空就使用比较器
    if (cpr != null) {
        do {
            parent = t;
            cmp = cpr.compare(key, t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
            	// 存在与给定key的键就替换
                return t.setValue(value);
        } while (t != null);
    }
    // 如果没有比较器就使用键的compareTo方法,所以这里键要实现Comparable接口
    else {
        if (key == null)
            throw new NullPointerException();
        @SuppressWarnings("unchecked")
            Comparable<? super K> k = (Comparable<? super K>) key;
        do {
            parent = t;
            cmp = k.compareTo(t.key);
            if (cmp < 0)
                t = t.left;
            else if (cmp > 0)
                t = t.right;
            else
                return t.setValue(value);
        } while (t != null);
    }
    // 这里说明红黑树中没有指定key的键
    Entry<K,V> e = new Entry<>(key, value, parent);
    // 根据大小添加到红黑树中
    if (cmp < 0)
        parent.left = e;
    else
        parent.right = e;
    // 插入后可能导致红黑树不平衡
    fixAfterInsertion(e);
    size++;
    modCount++;
    return null;
}

下面介绍另一个构造方法。

public TreeMap(SortedMap<K, ? extends V> m) {
    comparator = m.comparator();
    try {
    	// 根据有序map来构建
        buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }
}

private void buildFromSorted(int size, Iterator<?> it,
                             java.io.ObjectInputStream str,
                             V defaultVal)
    throws  java.io.IOException, ClassNotFoundException {
    this.size = size;
    root = buildFromSorted(0, 0, size-1, computeRedLevel(size),
                           it, str, defaultVal);
}

// 使用递归来构建,类似于将有序数组转换为搜索二叉树形式
private final Entry<K,V> buildFromSorted(int level, int lo, int hi,
                                         int redLevel,
                                         Iterator<?> it,
                                         java.io.ObjectInputStream str,
                                         V defaultVal)
    throws  java.io.IOException, ClassNotFoundException {
    /*
     * Strategy: The root is the middlemost element. To get to it, we
     * have to first recursively construct the entire left subtree,
     * so as to grab all of its elements. We can then proceed with right
     * subtree.
     *
     * The lo and hi arguments are the minimum and maximum
     * indices to pull out of the iterator or stream for current subtree.
     * They are not actually indexed, we just proceed sequentially,
     * ensuring that items are extracted in corresponding order.
     */

    if (hi < lo) return null;

    int mid = (lo + hi) >>> 1;

    Entry<K,V> left  = null;
    if (lo < mid)
        left = buildFromSorted(level+1, lo, mid - 1, redLevel,
                               it, str, defaultVal);

    // extract key and/or value from iterator or stream
    K key;
    V value;
    if (it != null) {
        if (defaultVal==null) {
            Map.Entry<?,?> entry = (Map.Entry<?,?>)it.next();
            key = (K)entry.getKey();
            value = (V)entry.getValue();
        } else {
            key = (K)it.next();
            value = defaultVal;
        }
    } else { // use stream
        key = (K) str.readObject();
        value = (defaultVal != null ? defaultVal : (V) str.readObject());
    }

    Entry<K,V> middle =  new Entry<>(key, value, null);

    // color nodes in non-full bottommost level red
    if (level == redLevel)
        middle.color = RED;

    if (left != null) {
        middle.left = left;
        left.parent = middle;
    }

    if (mid < hi) {
        Entry<K,V> right = buildFromSorted(level+1, mid+1, hi, redLevel,
                                           it, str, defaultVal);
        middle.right = right;
        right.parent = middle;
    }

    return middle;
}

3、方法介绍

public int size() {
    return size;
}

返回元素个数。

public boolean containsKey(Object key) {
    return getEntry(key) != null;
}

final Entry<K,V> getEntry(Object key) {
    // Offload comparator-based version for sake of performance
    // 首先判断是否根据比较器来遍历
    if (comparator != null)
        return getEntryUsingComparator(key);
    if (key == null)
        throw new NullPointerException();
    @SuppressWarnings("unchecked")
        Comparable<? super K> k = (Comparable<? super K>) key;
    Entry<K,V> p = root;
    while (p != null) {
        int cmp = k.compareTo(p.key);
        if (cmp < 0)
            p = p.left;
        else if (cmp > 0)
            p = p.right;
        else
            return p;
    }
    return null;
}

final Entry<K,V> getEntryUsingComparator(Object key) {
    @SuppressWarnings("unchecked")
        K k = (K) key;
    Comparator<? super K> cpr = comparator;
    if (cpr != null) {
        Entry<K,V> p = root;
        while (p != null) {
            int cmp = cpr.compare(k, p.key);
            if (cmp < 0)
                p = p.left;
            else if (cmp > 0)
                p = p.right;
            else
                return p;
        }
    }
    return null;
}

查看映射中是否包含指定key的键值对。

final Entry<K,V> getCeilingEntry(K key) {
    Entry<K,V> p = root;
    while (p != null) {
        int cmp = compare(key, p.key);
        if (cmp < 0) {
            if (p.left != null)
                p = p.left;
            else
                return p;
        } else if (cmp > 0) {
            if (p.right != null) {
                p = p.right;
            } else {
                Entry<K,V> parent = p.parent;
                Entry<K,V> ch = p;
                while (parent != null && ch == parent.right) {
                    ch = parent;
                    parent = parent.parent;
                }
                return parent;
            }
        } else
            return p;
    }
    return null;
}

获取指定键对应的条目; 如果不存在这样的条目,则返回大于指定键的最小键的条目; 如果不存在这样的条目(即,树中最大的键小于指定的键),则返回null 。
没脑汁了,改天再看。

public V remove(Object key) {
    Entry<K,V> p = getEntry(key);
    if (p == null)
        return null;

    V oldValue = p.value;
    deleteEntry(p);
    return oldValue;
}

private void deleteEntry(Entry<K,V> p) {
    modCount++;
    size--;

    // If strictly internal, copy successor's element to p and then make p
    // point to successor.
    if (p.left != null && p.right != null) {
        Entry<K,V> s = successor(p);
        p.key = s.key;
        p.value = s.value;
        p = s;
    } // p has 2 children

    // Start fixup at replacement node, if it exists.
    Entry<K,V> replacement = (p.left != null ? p.left : p.right);

    if (replacement != null) {
        // Link replacement to parent
        replacement.parent = p.parent;
        if (p.parent == null)
            root = replacement;
        else if (p == p.parent.left)
            p.parent.left  = replacement;
        else
            p.parent.right = replacement;

        // Null out links so they are OK to use by fixAfterDeletion.
        p.left = p.right = p.parent = null;

        // Fix replacement
        if (p.color == BLACK)
            fixAfterDeletion(replacement);
    } else if (p.parent == null) { // return if we are the only node.
        root = null;
    } else { //  No children. Use self as phantom replacement and unlink.
        if (p.color == BLACK)
            fixAfterDeletion(p);

        if (p.parent != null) {
            if (p == p.parent.left)
                p.parent.left = null;
            else if (p == p.parent.right)
                p.parent.right = null;
            p.parent = null;
        }
    }
}

static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t) {
    if (t == null)
        return null;
    // 右子树不为空,找到右子树最左面的元素
    else if (t.right != null) {
        Entry<K,V> p = t.right;
        while (p.left != null)
            p = p.left;
        return p;
    // 右子树为空,回溯
    } else {
        Entry<K,V> p = t.parent;
        Entry<K,V> ch = t;
        while (p != null && ch == p.right) {
            ch = p;
            p = p.parent;
        }
        return p;
    }
}

删除方法首先判断是否是叶子节点,如果不是找到后继节点进行替换。

public void clear() {
    modCount++;
    size = 0;
    root = null;
}

清空。

public Object clone() {
    TreeMap<?,?> clone;
    try {
        clone = (TreeMap<?,?>) super.clone();
    } catch (CloneNotSupportedException e) {
        throw new InternalError(e);
    }

    // Put clone into "virgin" state (except for comparator)
    clone.root = null;
    clone.size = 0;
    clone.modCount = 0;
    clone.entrySet = null;
    clone.navigableKeySet = null;
    clone.descendingMap = null;

    // Initialize clone with our mappings
    try {
        clone.buildFromSorted(size, entrySet().iterator(), null, null);
    } catch (java.io.IOException cannotHappen) {
    } catch (ClassNotFoundException cannotHappen) {
    }

    return clone;
}

浅克隆。

public Map.Entry<K,V> firstEntry() {
    return exportEntry(getFirstEntry());
}

final Entry<K,V> getFirstEntry() {
    Entry<K,V> p = root;
    if (p != null)
        while (p.left != null)
            p = p.left;
    return p;
}

// 包装一下
static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
    return (e == null) ? null :
        new AbstractMap.SimpleImmutableEntry<>(e);
}

返回红黑树中最左面元素。

public Map.Entry<K,V> lastEntry() {
    return exportEntry(getLastEntry());
}

final Entry<K,V> getLastEntry() {
    Entry<K,V> p = root;
    if (p != null)
        while (p.right != null)
            p = p.right;
    return p;
}

返回红黑树中最右面元素。

public Map.Entry<K,V> pollFirstEntry() {
    Entry<K,V> p = getFirstEntry();
    Map.Entry<K,V> result = exportEntry(p);
    if (p != null)
        deleteEntry(p);
    return result;
}

/**
 * @since 1.6
 */
public Map.Entry<K,V> pollLastEntry() {
    Entry<K,V> p = getLastEntry();
    Map.Entry<K,V> result = exportEntry(p);
    if (p != null)
        deleteEntry(p);
    return result;
}

同理。

public Map.Entry<K,V> lowerEntry(K key) {
    return exportEntry(getLowerEntry(key));
}

public K lowerKey(K key) {
    return keyOrNull(getLowerEntry(key));
}

public Map.Entry<K,V> floorEntry(K key) {
    return exportEntry(getFloorEntry(key));
}

public K floorKey(K key) {
    return keyOrNull(getFloorEntry(key));
}

public Map.Entry<K,V> ceilingEntry(K key) {
    return exportEntry(getCeilingEntry(key));
}

public K ceilingKey(K key) {
    return keyOrNull(getCeilingEntry(key));
}

public Map.Entry<K,V> higherEntry(K key) {
    return exportEntry(getHigherEntry(key));
}

public K higherKey(K key) {
    return keyOrNull(getHigherEntry(key));
}

返回相应的键值对。

public Set<K> keySet() {
	// 返回一个导航集合视图
    return navigableKeySet();
}

public NavigableSet<K> navigableKeySet() {
    KeySet<K> nks = navigableKeySet;
    // 首次调用先创建
    return (nks != null) ? nks : (navigableKeySet = new KeySet<>(this));
}

static final class KeySet<E> extends AbstractSet<E> implements NavigableSet<E> {
    private final NavigableMap<E, ?> m;
    KeySet(NavigableMap<E,?> map) { m = map; }

	// 迭代器根据传递过来的Map类型来返回向相应的迭代器
    public Iterator<E> iterator() {
        if (m instanceof TreeMap)
            return ((TreeMap<E,?>)m).keyIterator();
        else
            return ((TreeMap.NavigableSubMap<E,?>)m).keyIterator();
    }

    public Iterator<E> descendingIterator() {
        if (m instanceof TreeMap)
            return ((TreeMap<E,?>)m).descendingKeyIterator();
        else
            return ((TreeMap.NavigableSubMap<E,?>)m).descendingKeyIterator();
    }
    
    ...
}

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;
    }
}

final Entry<K,V> nextEntry() {
    Entry<K,V> e = next;
    if (e == null)
        throw new NoSuchElementException();
    if (modCount != expectedModCount)
        throw new ConcurrentModificationException();
    // 可以看到,这个迭代器的遍历是通过successor方法找到当前节点的后继节点来实现的
    next = successor(e);
    lastReturned = e;
    return e;
}

这是一个keySet集合的迭代器遍历next方法流程,剩下的方法和类都是跟各种集合以及其遍历顺序有关的,我就不写了。
完结,撒花★,°:.☆( ̄▽ ̄)/$:.°★

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值