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]