一天一个类,一点也不累之TreeSet

时间:2023-03-09 16:01:29
一天一个类,一点也不累之TreeSet

一天一个类,一点也不累。

一天一个类,一点也不累之TreeSet

现在要说的是---TreeSet

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

说句实话自己没怎么用过这个*_*

--》A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

如上,TreeSet实现了NavigableSet,这就要求元素是按照自然顺序来排序的或者使用Comparator比较器来实现

--》This implementation provides guaranteed log(n) time cost for the basic operations (addremove and contains).

  像上面说的一些基本操作他们的时间复杂度在Log(n)

--》Note that this implementation is not synchronized

还是这句话,他也是非线程安全的。

感谢!!~~ 同样给我们提供了线程安全的方式:

  SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

【TreeSet的内部实现也是使用TreeMap来实现的】

1、构造方法:

  他提供了很多种的构造方法

  public TreeSet();

  public TreeSet(Comparator<? super E> comparator);

  public TreeSet(Collection<? extends E> c)

  public TreeSet(SortedSet<E> s)

2、迭代器

  是否大家还记得LinkedList提供了一种倒序迭代器。同样TreeSet也提供了。

   public Iterator<E> iterator() {
return m.navigableKeySet().iterator();
}

由于在TreeSet中维护这一个NavigableSet m,所有迭代器的返回只使用了他的KeySet的迭代器。

3、一些特殊的使用方法:

  public E first() {

    return m.firstKey();
  } 获取第一个元素

同样也有获取最后一个元素last()

  public E lower(E e) {
return m.lowerKey(e);
}

获取比e小的最接近的元素。

    public E floor(E e) {
return m.floorKey(e);
}

获取大于或者等于e的最小元素

与之相对的ceiling

与lower相对的是higher

想要学好这个类首先要了解NavigableSet