Java集合之TreeSet集合

本文详细介绍了Java中的TreeSet集合,包括其初始化、添加元素、删除元素、查询元素等操作,强调了其基于红黑树的数据结构,元素唯一且有序的特点。此外,还探讨了遍历TreeSet集合的不同方法。
摘要由CSDN通过智能技术生成


前言

TreeSet集合底层数据结构采用红黑树实现,元素唯一且已经排好序。
TreeSet集合继承了AbstractSet类,实现了NavigableSet接口。其框架图如下:
在这里插入图片描述
蓝色代表接口,黑体代表类。

一、TreeSet集合初始化

  • TreeSet():无参构造,初始容量为0。源码如下:
   /**
     * 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>());
    }

该构造函数调用了TreeSet集合中的另一个有参构造,其参数可以是NavigableMap接口的任何实现类。

  • TreeSet(NavigableMap<E,Object> m):有参构造,参数是NavigableMap接口的实现类。源码如下:
  /**
     * Constructs a set backed by the specified navigable map.
     */
    TreeSet(NavigableMap<E,Object> m) {
   
        this.m = m;
    }

初始化本集合中的m变量,那m变量是啥呢?源码如下:

/**
     * The backing map.
     */
    private transient NavigableMap<E,Object> m;

该m变量是NavigableMap类型。所以,通过这两个构造函数可以看出TreeSet集合底层就是NavigableMap的各种实现类。

  • TreeSet(Collection<? extends E> c):有参构造,参数可以是List、Set接口的所有实现类。源码如下:
   /**
     * Constructs a new tree set containing the elements in the specified
     * collection, sorted according to the <i>natural ordering</i> 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.
     *
     * @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>
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值