TreeMap源码分析及高频面试问题答案

TreeMap实现了红黑树的结构,实现了有序map。

继承结构

public class TreeMap<K,V>
    extends AbstractMap<K,V>
    implements NavigableMap<K,V>, Cloneable, java.io.Serializable

在这里插入图片描述
TreeMap继承自AbstractMap,实现了NavigableMap接口。
1.AbstactMap实现了基本的map操作
2.NavigableMap接口继承自SortedMap接口,约定了comparator()方法,从而实现排序功能

成员变量

private final Comparator<? super K> comparator;
	//跟节点Node
    private transient Entry<K,V> root;
    //node数量
    private transient int size = 0;
    //改变的次数,实现fastfail
    private transient int modCount = 0;
    

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;

    Entry(K key, V value, Entry<K,V> parent) {
        this.key = key;
        this.value = value;
        this.parent = parent;
    }
    public K getKey() {
        return key;
    }

    public V getValue() {
        return value;
    }

    public V setValue(V value) {
        V oldValue = this.value;
        this.value = value;
        return oldValue;
    }

    public boolean equals(Object o) {
        if (!(o instanceof Map.Entry))
            return false;
        Map.Entry<?,?> e = (Map.Entry<?,?>)o;

        return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
    }

    public int hashCode() {
        int keyHash = (key==null ? 0 : key.hashCode());
        int valueHash = (value==null ? 0 : value.hashCode());
        return keyHash ^ valueHash;
    }

    public String toString() {
        return key + "=" + value;
    }
}

可以看到节点主要有这样几个属性,父节点,左节点和右节点,以及节点的红黑属性。

构造方法

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) {
    }
}

可以传入一个map 或者sortedMap

增/改:put(k,v)

 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;
                //将key进行比较
                cmp = cpr.compare(key, t.key);
                //小于0 t迭代为左侧,否则为右侧节点,迭代后的t==null ,即为要插入的位置(不准确,包含左右中可能)
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        //同上,不过是对key使用自然排序
        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);
        }
        //生成node节点
        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;
    }

删:remove 操作

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

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

删除操作包含了getEntry方法,和deleteEntry方法
getEntry

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

可以看到,是使用二分法,从根元素找到指定元素返回。

deleteMap

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

查:get()

public V get(Object key) {
     Entry<K,V> p = getEntry(key);
     return (p==null ? null : p.value);
 }

上文已说,通过getEntry二分查找。

面试中经常问到的相关问题:

1.说一下TreeMap的数据结构
TreeMap 实现了一个红黑树结构的map,实现了有序存取。
2.时间复杂度是多少?
查找、插入、删除在最坏情况下的复杂度都是O(lgN)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值