I have a generic class which bundles an Object and an order:
public class OrderedObject<T> {
private int order;
private T object;
public OrderedObject(int order, T object) {
this.order = order;
this.object = object;
}
public int getOrder() {
return order;
}
public T getObject() {
return object;
}
}
I developed a Set
implementation which stores OrderedObject<T>
instances and wants to produce an Iterator<T>
enumerating in the order enforced by the built-in order:
public class OrderedObjectSet<T> extends AbstractSet<T> implements Set<T> {
Set<OrderedObject<T>> s = new HashSet<OrderedObject<T>>();
public boolean add(int order, T object) {
return s.add(new OrderedObject<T>(order, object));
}
public Iterator<T> iterator() {
return new OrderedObjectSetIterator<T>();
}
public int size() {
return s.size();
}
private class OrderedObjectSetIterator<T> implements Iterator<T> {
private int index;
public boolean hasNext() {
return index < s.size();
}
public T next() {
T object = null;
for (Iterator<OrderedObject<T>> it = s.iterator(); it.hasNext(); ) {
OrderedObject<T> o = it.next();
if (o.getOrder() == index) {
object = o.getObject();
}
}
index++;
return object;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
The latter class does not compile because there seems to some confusion of types in the Iterator
initialization at
for (Iterator<OrderedObject<T>> it = s.iterator(); it.hasNext(); ) {
What do I overlook?