Java基础 之 TreeSet源码分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34083066/article/details/86767745

既然叫treeSet,那么顾名思义他是set接口的一个实现类。

都说Set接口的实现都是具有排序和去重功能的。

那么今天从源码分析I一下,TreeSet的去重和排序是如何做到的。

我们再开看下这个类的定义和他的构造器。

public class TreeSet<E> extends AbstractSet<E>
    implements NavigableSet<E>, Cloneable, java.io.Serializable
{
    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;

    // Dummy value to associate with an Object in the backing Map
    private static final Object PRESENT = new Object();

    /**
     * Constructs a set backed by the specified navigable map.
     */
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

    /**
     * Constructs a new, empty tree set, sorted according to the
     * natural ordering of its elements.  All elements inserted into
     * the set must implement the {@link Comparable} interface.
     * Furthermore, all such elements must be <i>mutually
     * comparable</i>: {@code e1.compareTo(e2)} must not throw a
     * {@code ClassCastException} for any elements {@code e1} and
     * {@code e2} in the set.  If the user attempts to add an element
     * to the set that violates this constraint (for example, the user
     * attempts to add a string element to a set whose elements are
     * integers), the {@code add} call will throw a
     * {@code ClassCastException}.
     */
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }

TeeSet首先继承了AbstractSet抽象类,而AbstractSet又实现类Set接口。

再看一下他实现的另一个接口,NavigableSet接口。NavigableSet接口内又继承了SortedSet接口。

所以这里得出一个结论:

TreeSet是Set的一个实现;有排序功能的。

那么他的排序如何实现的?其实我们再往下看。

假如我们从空构造器开始分析,从这个构造器可以看出来:

这个TreeSet在初始化时,构造器内部声明了一个TreeMap对象。

和之前我们看过的hashSet一样,key是我们要保存的值的类型,value是一个object。

所以看得出来,TreeSet的内部实现是一个TreeMap。

而TreeMap的实现是红黑树,有关TreeMap的内容详见传送门:

Java基础 之 TreeMap源码分析

结论就是TreeSet的内部实现是一个TeeMap。而TreeMap的数据结构是一个红黑树。

所以TreeSet的排序和去重来源于红黑树。

再看一下add方法

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

再看一下添加方法,也是调用的map的put的方法。把我们要保存的值放到map的key中,而value都指向堆内存中一个object对象。

就先分析到这吧,有关TreeSet的一些自己的特殊用法 不在Set接口内的,有空再写吧。

猜你喜欢

转载自blog.csdn.net/qq_34083066/article/details/86767745