TreeSet、HashSet、LinkedHashSet

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

一、类图

       

二、要点

1.  TreeSet 是基于 TreeMap 实现的,内置了 NavigableMap,构造函数直接使用 TreeMap

    /**
     * The backing map.
     */
    private transient NavigableMap<E,Object> 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>());
    }

    /**
     * Constructs a new, empty tree set, sorted according to the specified
     * comparator.  All elements inserted into the set must be <i>mutually
     * comparable</i> by the specified comparator: {@code comparator.compare(e1,
     * 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, the
     * {@code add} call will throw a {@code ClassCastException}.
     *
     * @param comparator the comparator that will be used to order this set.
     *        If {@code null}, the {@linkplain Comparable natural
     *        ordering} of the elements will be used.
     */
    public TreeSet(Comparator<? super E> comparator) {
        this(new TreeMap<>(comparator));
    }

2.  TreeSet 提供逆序迭代 descendingSet

3.  TreeSet 内部实现都是委托给 TreeMap 实现了

    public boolean contains(Object o) {
        return m.containsKey(o);
    }

4.   HashSet 是基于 HashMap 实现的

    public HashSet() {
        map = new HashMap<>();
    }

5.   LinkedHashSet 基于 HashMap 的子类 LinkedHashMap 实现

    public LinkedHashSet(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
    }

    // super method

    HashSet(int initialCapacity, float loadFactor, boolean dummy) {
        map = new LinkedHashMap<>(initialCapacity, loadFactor);
    }  

猜你喜欢

转载自blog.csdn.net/shida_csdn/article/details/81429259