我的jdk源码(二十):TreeSet类

一、概述

    TreeSet类的构造方法底层调用的是TreeMap类的构造方法,也就是说,TreeSet类底层也是红黑树的结构,红黑树的结构这里不再赘述,小伙伴们可以在《我的jdk源码(十九):TreeMap类 红黑树实现的map结构》一文中看到。类似HashSet与HashMap的关系,TreeSet类中,也是将要添加的对象E作为key-value组成的TreeSet元素中的key,value存的也是一个预先就声明好的空对象, 所以当你既想利用Map的高效查找特性,又想维持元素特定的顺序,又想保证元素(kv键值对)的唯一性,那么你就需要用到TreeSet类。

二、源码分析

    1. 类的声明

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable

    可以看到TreeSet类的声明与TreeMap类的声明结构是一致的,只是类型由TreeMap的KV变为了泛型E。也就是说TreeSet是允许添加任何Object对象的,并且此对象在TreeSet只存放一个。

    TreeSet类继承自AbstractSet类,并且实现了NavigableSet接口、Cloneable接口以及Serializable接口。具体如下:

        a. 继承于AbstractSet,所以它是一个Set。

        b. 实现了NavigableSet接口,意味着它支持一系列的导航方法。

        c. 实现了Cloneable接口,意味着它能被克隆。

        d. 实现了java.io.Serializable接口,意味着它支持序列化。

    2. 成员变量

    //使用NavigableMap的key来保存Set集合的元素,一些导航方法操作的都是这个集合
    private transient NavigableMap<E,Object> m;

    //定义一个空对象,在构建Map的元素的时候,value就是放的这个对象
    private static final Object PRESENT = new Object();

    //序列化id
    private static final long serialVersionUID = -2479143000061671589L;

    成员变量上值得注意的是,和HashSet定义的成员变量PRESENT一样,都是先定义了一个空对象,插入元素的时候,将这个空对象放入value中。

    3. 构造方法

    //以自然排序方式创建一个新的TreeMap,使用该TreeMap的key来保存Set集合的元素
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }

    //以特定的比较器的排序规则进行排序创建的TreeMap
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

    //参数为一个集合的构造方法,调用第一个构造方法构建TreeMap,并添加所有元素
    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    //参数为有序集合的构造方法,调用第二个构造方法构建TreeMap,并添加所有元素
    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }

    构造方法中我们就能清晰的知道,TreeSet类在初始化的时候,就是创建了一个TreeMap的实例。addAll()方法中也是在调用的TreeSet类add()方法来添加的元素。

    4. add()方法

    public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }

    TreeSet类的add()方法就是将要保存的对象e作为Map元素的key,用声明的空对象PRESENT作为value进行保存的。

    5. 其他方法

    //判断set是否为空
    public boolean isEmpty() {
        return m.isEmpty();
    }
    //判断set中是否包含元素o
    public boolean contains(Object o) {
        return m.containsKey(o);
    }
    
    //将元素o从set中移除
    public boolean remove(Object o) {
        return m.remove(o)==PRESENT;
    }
    
    //清空set
    public void clear() {
        m.clear();
    }

    //添加一个集合
    public  boolean addAll(Collection<? extends E> c) {
        // Use linear-time version if applicable
        if (m.size()==0 && c.size() > 0 &&
            c instanceof SortedSet &&
            m instanceof TreeMap) {
            SortedSet<? extends E> set = (SortedSet<? extends E>) c;
            TreeMap<E,Object> map = (TreeMap<E, Object>) m;
            Comparator<?> cc = set.comparator();
            Comparator<? super E> mc = map.comparator();
            //当传入集合是SortedSet并且比较器和底层TreeMap的比较器一致时,直接调用TreeMap的添加函数addAllForTreeSet
            //否则通过迭代器遍历一次调用add方法进行添加
            if (cc==mc || (cc != null && cc.equals(mc))) {
                map.addAllForTreeSet(set, PRESENT);
                return true;
            }
        }
        return super.addAll(c);
    }   

    //返回一个子集合
    public NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                                  E toElement,   boolean toInclusive) {
        return new TreeSet<>(m.subMap(fromElement, fromInclusive,
                                       toElement,   toInclusive));
    }
    
    //返回set的头部
    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
        return new TreeSet<>(m.headMap(toElement, inclusive));
    }
    
    //返回set的尾部
    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
        return new TreeSet<>(m.tailMap(fromElement, inclusive));
    }
    
    //返回一个子集合
    public SortedSet<E> subSet(E fromElement, E toElement) {
        return subSet(fromElement, true, toElement, false);
    }

    //返回m使用的比较器
    public Comparator<? super E> comparator() {
        return m.comparator();
    }

    //返回第一个元素
    public E first() {
        return m.firstKey();
    }
    //返回最后一个元素
    public E last() {
        return m.lastKey();
    }

    //返回set中小于e的最大的元素
    public E lower(E e) {
        return m.lowerKey(e);
    }

    //返回set中小于/等于e的最大元素
    public E floor(E e) {
        return m.floorKey(e);
    }

    //返回set中大于/等于e的最大元素
    public E ceiling(E e) {
        return m.ceilingKey(e);
    }

    //返回set中大于e的最小元素
    public E higher(E e) {
        return m.higherKey(e);
    }

    //获取TreeSet中第一个元素,并从Set中删除该元素
    public E pollFirst() {
        Map.Entry<E,?> e = m.pollFirstEntry();
        return (e == null) ? null : e.getKey();
    }

    //获取TreeSet中最后一个元素,并从Set中删除该元素
    public E pollLast() {
        Map.Entry<E,?> e = m.pollLastEntry();
        return (e == null) ? null : e.getKey();
    }

    //克隆方法
    public Object clone() {
        TreeSet<E> clone = null;
        try {
            clone = (TreeSet<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError();
        }

        clone.m = new TreeMap<>(m);
        return clone;
    }

    //将对象写入到输出流中。
    private void writeObject(java.io.ObjectOutputStream s)
        throws java.io.IOException {
        // Write out any hidden stuff
        s.defaultWriteObject();

        // Write out Comparator
        s.writeObject(m.comparator());

        // Write out size
        s.writeInt(m.size());

        // Write out all elements in the proper order.
        for (E e : m.keySet())
            s.writeObject(e);
    }

    //从输入流中读取对象的信息
    private void readObject(java.io.ObjectInputStream s)
        throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden stuff
        s.defaultReadObject();

        // Read in Comparator
        Comparator<? super E> c = (Comparator<? super E>) s.readObject();

        // Create backing TreeMap
        TreeMap<E,Object> tm;
        if (c==null)
            tm = new TreeMap<>();
        else
            tm = new TreeMap<>(c);
        m = tm;

        // Read in size
        int size = s.readInt();

        tm.readTreeSet(size, s, PRESENT);
    }

    TreeSet类的其他方法没有太需要注意的点。

三、总结

     本文主要是介绍了TreeSet类除红黑树结构的方法外其他的一些方法与特性。TreeSet类主要应用场景是在需要利用Map的高效查找特性,又想维持元素特定的顺序的时候,还想想保证元素(kv键值对)的唯一性,也是着重要掌握红黑树的特性以及红黑树维护自身特性的方法过程,包括各种情况的判断以及左旋右旋对树结构的影响。关于红黑树的结构在我的上一篇文章《我的jdk源码(十九):TreeMap类 红黑树实现的map结构》中已经剖析得非常详细,强烈安利给还没看过或者还没懂红黑树的小伙伴!

    TreeMap类具有以下几点特点:

    1. 不允许存放空数据

    2. 不允许重复数据

    3. TreeSet中的元素是有序的,按照key的自然顺序或者指定的比较器的比较规则进行排序

    4. 是非线程安全的

    敬请期待《我的jdk源码(二十一):ConcurrentHashMap类》。

    更多精彩内容,敬请扫描下方二维码,关注我的微信公众号【Java觉浅】,获取第一时间更新哦!

猜你喜欢

转载自blog.csdn.net/qq_34942272/article/details/106642407