Custom Java Iterator with Type Confusion

I have a general class that binds 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 that stores instances of OrderedObject<T> and wants to enumerate Iterator<T> in the order set 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 last class does not compile, because there is some type confusion in Iterator initialization in

 for (Iterator<OrderedObject<T>> it = s.iterator(); it.hasNext(); ) { 

What I do not like?

+4
java iterator generics
source share
1 answer

The confusion is that the inner class OrderedObjectSetIterator introduces a generic type called the same ( T ) as the outer class. The Eclipse IDE shows a warning:

 The type parameter T is hiding the type T 

So, I think you do not need to enter another type of parameter, just use the same as the outer class.

Basically, an inner class will be defined as:

 private class OrderedObjectSetIterator implements Iterator<T> { .... 

Iterator method like:

 public Iterator<T> iterator() { return new OrderedObjectSetIterator(); } 
+5
source share

All Articles