Bart Strubbe
Bart Strubbe

Reputation: 107

Custom Java Iterator with type confusion

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?

Upvotes: 4

Views: 7021

Answers (1)

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24251

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

The type parameter T is hiding the type T   

So I guess you don't need to introduce another parameter type, just use the same as the outer class defines.

Basically, the inner class would be defined as:

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

And the iterator method as:

public Iterator<T> iterator() {
    return new OrderedObjectSetIterator();
}

Upvotes: 5

Related Questions