Java集合框架:了解TreeSet

本文详细探讨了Java中的TreeSet,它基于TreeMap实现,支持序列化和克隆。TreeSet实现了Serializable、Cloneable和NavigableSet接口,提供了有序的元素存储和多种操作。文章分析了TreeSet的构造函数、迭代器、增删方法、子集操作、匹配元素功能以及其他实用方法。同时,总结指出TreeSet依赖红黑树保证排序,并要求元素实现Comparable接口,确保全序性,且它不是线程安全的。
摘要由CSDN通过智能技术生成

TreeSet

基于TreeMap实现的树集

目录

TreeSet继承关系

TreeSet源码分析 

TreeSet总结


TreeSet继承关系

TreeSet实现了Serializable接口,支持序列化,可通过序列化传输

TreeSet实现了Cloneable接口,覆盖了clone()方法,能被克隆

TreeSet实现了NavigableSet接口,可以元素匹配,升/降序访问和遍历元素,返回集的视图

TreeSet实现了List接口和继承了Abstractlist抽象类,可进行集合相关的操作

TreeSet源码分析 

TreeSet构造函数:

/**
     * 构造一个由指定的NavigableMap支持的集
     */
    TreeSet(NavigableMap<E,Object> m) {
        this.m = m;
    }

    /**
     * 构造一个树集, 并根据其元素的自然顺序排序, 集中的所有元素都须实现 Comparable 接口
     * 所有元素都必须相互可比, 否则方法将抛出ClassCastException异常
     */
    public TreeSet() {
        this(new TreeMap<>());
    }

    /**
     * 构造一个新树集, 根据指定的比较器排序
     * 集中的所有元素必须与指定的比较器相互比较, 否则方法将抛出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));
    }

    /**
     * 构造一个包含指定集合中元素的新树集, 根据元素的自然顺序排序
     * 插入集中的所有元素必须实现Comparable接口, 所有元素都必须相互可比
     *
     * @param c collection whose elements will comprise the new set
     * @throws ClassCastException if the elements in {@code c} are
     *         not {@link Comparable}, or are not mutually comparable
     * @throws NullPointerException if the specified collection is null
     */
    public TreeSet(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     * 构造一个新的树集, 与指定排序集有 相同元素 和 同一顺序
     *
     * @param s sorted set whose elements will comprise the new set
     * @throws NullPointerException if the specified sorted set is null
     */
    public TreeSet(SortedSet<E> s) {
        this(s.comparator());
        addAll(s);
    }

TreeSet迭代器相关方法:

    /**
     * 升序方式返回元素迭代器
     *
     * @return an iterator over the elements in this set in ascending order
     */
    public Iterator<E> iterator() {
        return m.navigableKeySet().iterator();
    }

    /**
     * 降序方式返回元素迭代器
     *
     * @return an iterator over the elements in this set in descending order
     * @since 1.6
     */
    public Iterator<E&
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值