I want to go over the objects inside my TreeSet
, I can do it by making an array using toArray
but I don't need to go over all of the objects in the Set.
How can I go over the objects in the Set (starting with the first than the second etc') ?
And another small question about TreeSet
: Can I keep the objects in the TreeSet
sorted (so the first object will be with the smallest key etc') ?
edit: say I have a class myInt (with int myInteger) and I want to use it in TreeSet with a different oredering than the natural one, what do I need to define in my class (myInt) to do this ?
How can I go over the objects in the Set
The easiest way to iterate over the items of the set is like so:
SortedSet<T> set = new TreeSet<T>();
for (T elem : set) {
// use elem
}
Can I keep the objects in the TreeSet sorted
TreeSet
is automatically sorted, so you don't need to do anything.
I have a class MyInt (with int myInteger) and I want to use it in TreeSet with a different ordering than the natural one
You have two options:
Option 1: Make it implement 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`
}
}
Option 2: Supply a Comparator<MyInt>
when constructing the TreeSet
:
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 always keeps the objects sorted by how the objects compareTo (Comparable interface) is implemented. (Or you can pass a separate Comparator into the TreeSet constructor.)
Since the SetTree implements iterable you can use a regular for each loop or use the iterator directly. In the javadocs it says that it will iterate in ascending order.
http://download.oracle.com/javase/6/docs/api/java/util/TreeSet.html#iterator ()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.