views:

179

answers:

1

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
higher()! Good find (or memory)! I was hunting around for something like ListIterator for Sets.
Michael Myers
It was a find -- I haven't used TreeSet before -- those API Specifications come in handy :)
coobird
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
This is only available in Java 1.6 and later by the way
newacct
@newacct: That's good to know, thank you for the information :)
coobird