欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java基础之TreeMap详解

程序员文章站 2022-03-24 08:13:27
一、写在前面treemap的底层数据结构是红黑树,且treemap可以实现集合元素的排序。所以treemap的源码需要实现:1.红黑树的数据结构,以及红黑树的节点插入,删除,以及红黑树的自平衡操作,如...

一、写在前面

treemap的底层数据结构是红黑树,且treemap可以实现集合元素的排序。

所以treemap的源码需要实现:

1.红黑树的数据结构,以及红黑树的节点插入,删除,以及红黑树的自平衡操作,如左旋,右旋,以及节点变色

2.红黑树需要支持按照指定的比较器进行排序,或者进行自然排序。

二、定义

public class treemap<k,v>
    extends abstractmap<k,v>
    implements navigablemap<k,v>, cloneable, java.io.serializable
public interface navigablemap<k,v> extends sortedmap<k,v> {

treemap

继承了abstractmap

实现了navigablemap,而navigablemap接口继承了sortedmap接口,sortedmap接口表示其实现类是一个有序集合

实现了cloneable,所以支持对象克隆

实现了serializable,所以支持对象序列化

三、成员变量

comparator

 /**
     * the comparator used to maintain order in this tree map, or
     * null if it uses the natural ordering of its keys.
     *
     * @serial
     */
    private final comparator<? super k> comparator;

外部指定的比较器。在创建treemap对象时可以指定。如果指定了比较器,则treemap插入键值对时,按照comparator比较排序。 

root

 private transient entry<k,v> root;

root指代treemap底层红黑树的根节点。 root的类型entry<k,v>就是红黑树节点的类型。

红黑树数据结构的实现就依赖于entry<k,v>

size

/**
     * the number of entries in the tree
     */
    private transient int size = 0;

 表示treemap集合中键值对个数。

modcount 

/**
     * the number of structural modifications to the tree.
     */
    private transient int modcount = 0;

表示treemap集合被结构化修改的次数。用于迭代器迭代过程中检测集合是否被结构化修改,若是,则fail-fast。

四、内部类

entry<k,v>

entry<k,v>是红黑树节点的代码实现,是实现红黑树数据结构的基础。

    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;
 
        /**
         * make a new cell with given key, value, and parent, and with
         * {@code null} child links, and black color.
         */
        entry(k key, v value, entry<k,v> parent) {
            this.key = key;
            this.value = value;
            this.parent = parent;
        }
 
        /**
         * returns the key.
         *
         * @return the key
         */
        public k getkey() {
            return key;
        }
 
        /**
         * returns the value associated with the key.
         *
         * @return the value associated with the key
         */
        public v getvalue() {
            return value;
        }
 
        /**
         * replaces the value currently associated with the key with the given
         * value.
         *
         * @return the value associated with the key before this method was
         *         called
         */
        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;
        }
    }

成员变量 

k key,v value分别是treemap集合中存储的键值对的键和值

entry<k,v> left 代表当前节点的左子节点

entry<k,v> right 代表当前节点的右子节点

entry<k,v> parent 代表当前节点的父节点

boolean color 代表当前节点的颜色,默认是黑色,为true

构造器

entry<k,v>只提供了一个构造器 entry(k key, v value, entry<k,v> parent)

即:创建一个红黑树节点,只需要指定其存储的键值信息,以及其父节点引用。不需要指定左孩子和右孩子,以及颜色。

成员方法

提供了getkey()方法返回当前节点的key值。

提供了getvalue(),setvalue(v v)分别用于获取value,以及覆盖value后返回oldvalue

重写了equals()方法用于判断两个红黑树节点是否相同。逻辑是:两个红黑树节点的key要么都为null,要么equals结果true,且,value要么都为null,要么equals结果为true。

重写了hashcode()方法。

重写了tostring()方法。

五、构造器

public treemap()

    public treemap() {
        comparator = null;
    }

无参构造器,即不指定比较器的构造器。

注意,此时插入集合的键值对的key的类型必须实现comparable接口,即提供自然排序能力,否则会报错类型转换异常。 

public treemap(comparator<? super k> comparator)

 public treemap(comparator<? super k> comparator) {
        this.comparator = comparator;
    }

指定比较器的构造器。

指定的比较器用于比较key,且comparator指定了泛型,即比较器比较的元素的类型必须是k或者k的父类类型。

public treemap(map<? extends k, ? extends v> m)

    public treemap(map<? extends k, ? extends v> m) {
        comparator = null;
        putall(m);
    }

 将非treemap集合转为treemap集合构造器

public treemap(sortedmap<k, ? extends v> 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集合转为treemap集合

六、成员方法

public v get(object key)

    public v get(object key) {
        entry<k,v> p = getentry(key);
        return (p==null ? null : p.value);
    }

treemap的get方法用于获取指定key的value。如果指定key没有对应的红黑树节点,则返回null,否则返回对应红黑树节点的value。

可以看到get方法实现依赖于getentry(object key)方法。

getentry(object key)方法是根据指定key找对应的红黑树节点并返回该节点。

final entry<k,v> getentry(object key)

    final entry<k,v> getentry(object key) {
        // offload comparator-based version for sake of performance
        if (comparator != null)//如果外部指定了比较器
            return getentryusingcomparator(key);//则使用指定比较器来查找
        if (key == null)//如果外部没有指定比较器,且要查找的key为null,则抛出空指针异常
            throw new nullpointerexception();
        @suppresswarnings("unchecked")//此时外部没有指定构造器,且要查的key不为null
            comparable<? super k> k = (comparable<? super k>) key;//检查key的类型是否实现了comparable接口,即是否实现了自然排序,如果实现了,则此处可以强转成功,否则会报错类型转换异常
        entry<k,v> p = root;
        while (p != null) {//从红黑树根节点开始使用key本身的自然排序进行比较
            int cmp = k.compareto(p.key);
            if (cmp < 0)//如果要查找的key小于树节点的key,则说明要找的key在当前节点的左子树上,则下次遍历从左子树的根节点开始
                p = p.left;
            else if (cmp > 0)//如果要查找的key大于树节点的key,则说明要找的key在当前节点的右子树上,则下次遍历从右子树的根节点开始
                p = p.right;
            else//如果要查找的key等于树节点的key,则该节点就是要找的,直接返回该节点
                return p;
        }
        return null;//如果上面遍历没有找到对应key的节点,则返回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;
    }

Java基础之TreeMap详解

 public v put(k key, v value)

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
                    return t.setvalue(value);
            } while (t != null);
        }
        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);
        }
        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;
    }
final int compare(object k1, object k2) {
        return comparator==null ? ((comparable<? super k>)k1).compareto((k)k2)
            : comparator.compare((k)k1, (k)k2);
    }
public v setvalue(v value) {
            v oldvalue = this.value;
            this.value = value;
            return oldvalue;
        }

  treemap的put方法用于插入一个键值对,

当插入的key在集合中不存在时,则put表示新增键值对,并返回null;

当插入的key在集合中存在时,则put表示覆盖已存在key对应的value,并返回老value。

Java基础之TreeMap详解

private void fixafterinsertion(entry<k,v> x)

  private void fixafterinsertion(entry<k,v> x) {//x是被插入的红黑树节点
        x.color = red;//默认被插入的节点都是红色
 
        while (x != null && x != root && x.parent.color == red) {//如果被插入节点不是根节点
            if (parentof(x) == leftof(parentof(parentof(x)))) {
                entry<k,v> y = rightof(parentof(parentof(x)));
                if (colorof(y) == red) {
                    setcolor(parentof(x), black);
                    setcolor(y, black);
                    setcolor(parentof(parentof(x)), red);
                    x = parentof(parentof(x));
                } else {
                    if (x == rightof(parentof(x))) {
                        x = parentof(x);
                        rotateleft(x);
                    }
                    setcolor(parentof(x), black);
                    setcolor(parentof(parentof(x)), red);
                    rotateright(parentof(parentof(x)));
                }
            } else {
                entry<k,v> y = leftof(parentof(parentof(x)));
                if (colorof(y) == red) {
                    setcolor(parentof(x), black);
                    setcolor(y, black);
                    setcolor(parentof(parentof(x)), red);
                    x = parentof(parentof(x));
                } else {
                    if (x == leftof(parentof(x))) {
                        x = parentof(x);
                        rotateright(x);
                    }
                    setcolor(parentof(x), black);
                    setcolor(parentof(parentof(x)), red);
                    rotateleft(parentof(parentof(x)));
                }
            }
        }
        root.color = black;//如果被插入的节点是根节点,则节点颜色改为黑色
    }

fixafterinsertion方法用于:当treemap插入红黑树节点后,导致红黑树不平衡时,treemap保持自平衡的自旋和变色操作。

该方法的入参就是插入的红黑树节点。

到此这篇关于java基础之treemap详解的文章就介绍到这了,更多相关java treemap详解内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!