位置:首页 > Java技术 > Java基础教程 > Java TreeSet类

Java TreeSet类

TreeSet中提供了使用存储树Set接口的一个实现。对象存储在排序,按升序排列。

访问和检索的时间是相当快,存储,必须迅速找到大量的排序信息时,这使得TreeSet的一个很好的选择。

TreeSet类支持四种构造函数。第一种形式构造一个空树组会以递增顺序根据其元素的自然顺序进行排序:

TreeSet( )

第二种形式生成包含c的元素树集。

TreeSet(Collection c)

第三种形式构造一个空树组将根据排版指定的比较器进行排序。

TreeSet(Comparator comp)

第四种形式生成包含ss的元素树组:

TreeSet(SortedSet ss)

除了从它的父类继承的方法,TreeSet中定义了以下方法:

SN 方法和描述
1 void add(Object o)
Adds the specified element to this set if it is not already present.
2 boolean addAll(Collection c) 
Adds all of the elements in the specified collection to this set.
3 void clear() 
Removes all of the elements from this set.
4 Object clone()
Returns a shallow copy of this TreeSet instance.
5 Comparator comparator()
Returns the comparator used to order this sorted set, or null if this tree set uses its elements natural ordering.
6 boolean contains(Object o) 
Returns true if this set contains the specified element.
7 Object first() 
Returns the first (lowest) element currently in this sorted set.
8 SortedSet headSet(Object toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement.
9 boolean isEmpty() 
Returns true if this set contains no elements.
10 Iterator iterator() 
Returns an iterator over the elements in this set.
11 Object last() 
Returns the last (highest) element currently in this sorted set.
12 boolean remove(Object o) 
Removes the specified element from this set if it is present.
13 int size() 
Returns the number of elements in this set (its cardinality).
14 SortedSet subSet(Object fromElement, Object toElement) 
Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive.
15 SortedSet tailSet(Object fromElement) 
Returns a view of the portion of this set whose elements are greater than or equal to fromElement.

例子:

下面的程序说明了几个由这个集合所支持的方法:

import java.util.*;

public class TreeSetDemo {

   public static void main(String args[]) {
      // Create a tree set
      TreeSet ts = new TreeSet();
      // Add elements to the tree set
      ts.add("C");
      ts.add("A");
      ts.add("B");
      ts.add("E");
      ts.add("F");
      ts.add("D");
      System.out.println(ts);
   }
}

这将产生以下结果:

[A, B, C, D, E, F]