2. java8 Set集合知识点

时间:2019-03-19
本文章向大家介绍2. java8 Set集合知识点,主要包括2. java8 Set集合知识点使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

集合:Set

Set集合包含有:EnumSet,SortedSet,HashSet,TreeSet,LinkHashSet,其中treeSet是SortedSet的进一步实现,LinkHashSet是HashSet的进一步实现。

 

1. EnumSet:EnumSet类是一种专为枚举类设计的集合类,EnumSet中的所有元素都必须是指定枚举类型的枚举值,该枚举类型在创建EnumSe类时显式或隐式的指定。EnumSet的集合元素也是有序的,EnumSet以枚举值在Enum类内的定义顺序来决定集合元素的顺序。

2. SortedSet接口,TreeSet实现类:无序无重复集合(Sorted:按照对象的比较函数对元素排序,而不是指元素的插入次序),由源码可见,底层实现是通过TreeMap的Key值来实现集合无重复元素。

    /**
     * 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>());
    }

TreeMap部分源码:元素结构Entry类:链表结构

 /**
     * Node in the Tree.  Doubles as a means to pass key-value pairs back to
     * user (see Map.Entry).
     */

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

 

3. HashSet:无序无重复集合,由源码可见,底层实现是通过HashMap的Key值来实现集合无序无重复元素,HashMap节点是一个单向链表

4.LinkedHashSet:无序无重复集合,由源码可见,底层实现是通过LinkHashMap(HashMap的进一步实现)的Key值来实现集合无序无重复元素,LinkHashMap节点是一个双向链表。