美文网首页
jdk源码分析之TreeSet

jdk源码分析之TreeSet

作者: shoulda | 来源:发表于2018-06-26 15:27 被阅读0次

1.TreeSet简介

与HashSet是基于HashMap实现一样,TreeSet同样是基于TreeMap实现的。
TreeMap是一个有序的二叉树,那么同理TreeSet同样也是一个有序的,他的作用是提供有序的set集合。

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

可以得知TreeSet继承与AbstractSet,实现NavigableSet,Cloneable,Serializable接口。

2.TreeSet中的变量

private transient NavigableMap<E,Object> m;
        
//PRESENT会被当做Map的value与key构建成键值对
 private static final Object PRESENT = new Object();

3.TreeSet中的构造方法

//默认构造方法,根据其元素的自然顺序进行排序
    public TreeSet() {
        this(new TreeMap<E,Object>());
    }
    
    //构造一个包含指定 collection 元素的新 TreeSet,它按照其元素的自然顺序进行排序。
    public TreeSet(Comparator<? super E> comparator) {
            this(new TreeMap<>(comparator));
    }
    
    //构造一个新的空 TreeSet,它根据指定比较器进行排序。
    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }
    
    //构造一个与指定有序 set 具有相同映射关系和相同排序的新 TreeSet。
    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }
    
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

4.TreeSet只要方法

  1. add:将指定的元素添加到此set中
public boolean add(E e) {
        return m.put(e, PRESENT)==null;
    }

2.addAll:将指定collection中的元素添加到set中

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<? super E> cc = (Comparator<? super E>) set.comparator();
            Comparator<? super E> mc = map.comparator();
            if (cc==mc || (cc != null && cc.equals(mc))) {
                map.addAllForTreeSet(set, PRESENT);
                return true;
            }
        }
        return super.addAll(c);
    }

3.ceiling:返回此set中大于等于给定元素的最小元素。

public E ceiling(E e) {
        return m.ceilingKey(e);
    }

4.clone:返回TreeSet实例的浅表副本,属于浅拷贝

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

5.comparator:返回对此set中的元素进行排序的比较器,如果此set使用其元素的自然排序,返回null。

public Comparator<? super E> comparator() {
        return m.comparator();
    }

相关文章

网友评论

      本文标题:jdk源码分析之TreeSet

      本文链接:https://www.haomeiwen.com/subject/omvpyftx.html