码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-04-29 23:10:05      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

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

技术分享

 现在要说的是---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也提供了。

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

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

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

  public E first() {

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

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

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

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

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

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

与之相对的ceiling

与lower相对的是higher

 

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

 

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

标签:

原文地址:http://www.cnblogs.com/plxx/p/4467465.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!