[英]Java: using TreeSet
我想要查看TreeSet
的對象,我可以通過使用toArray
創建一個數組來完成它,但我不需要遍歷Set中的所有對象。
如何查看Set中的對象(從第一個開始比第二個等)?
而關於另一個小問題TreeSet
:我能保留在物體TreeSet
排序(所以第一個對象將是具有最小鍵等')?
編輯:說我有一個類myInt(使用int myInteger)並且我想在TreeSet中使用它而不是自然的,我需要在我的類(myInt)中定義什么才能做到這一點?
如何查看Set中的對象
迭代集合項目的最簡單方法是:
SortedSet<T> set = new TreeSet<T>();
for (T elem : set) {
// use elem
}
我可以保持TreeSet中的對象排序
TreeSet
會自動排序,因此您無需執行任何操作。
我有一個類MyInt(使用int myInteger),我想在TreeSet中使用它,其順序與自然順序不同
您有兩種選擇:
選項1:使其實現Comparable<MyInt>
:
public class MyInt implements Comparable<MyInt> {
public int compareTo(MyInt o) {
// return -1 if `this` is less than `o`
// 0 if `this` is equal to `o`
// 1 of `this` is greater than `o`
}
}
選項2:構造TreeSet
時提供Comparator<MyInt>
:
public class MyIntCmp implements Comparator<MyInt> {
// implement compare() and equals() as per Comparator javadoc
}
SortedSet<T> set = new TreeSet<T>(new MyIntCmp());
for (MySetElementType element : mytreeset) {
}
TreeSet始終按照對象compareTo(Comparable interface)的實現方式對對象進行排序。 (或者您可以將單獨的Comparator傳遞給TreeSet構造函數。)
由於SetTree實現了iterable,因此您可以為每個循環使用常規或直接使用迭代器。 在javadoc中,它表示它將按升序迭代。
http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html#iterator ()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.