I was wondering if there was a way to accomplish this, or if there are alternative data structures. It has to be sorted, without duplicates, and have an iterator.
+8
A:
TreeSet
has an iterator
, is sorted, won't have duplicates, and is able to see the next higher element by using higher
.
For example:
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(1);
ts.add(4);
ts.add(4);
ts.add(3);
for (Integer i : ts) {
System.out.println("current: " + i + " next: " + ts.higher(i));
}
The output is:
current: 1 next: 3
current: 3 next: 4
current: 4 next: null
coobird
2009-05-29 16:38:30
higher()! Good find (or memory)! I was hunting around for something like ListIterator for Sets.
Michael Myers
2009-05-29 16:40:15
It was a find -- I haven't used TreeSet before -- those API Specifications come in handy :)
coobird
2009-05-29 16:41:56
Thanks, I had forgotten about higher. I guess I have to keep the current element in memory as that seems to be the only way to do it.
Soldier.moth
2009-05-29 16:50:54
This is only available in Java 1.6 and later by the way
newacct
2009-05-29 18:16:26
@newacct: That's good to know, thank you for the information :)
coobird
2009-05-30 03:33:18