Bartek
Bartek

Reputation: 23

Generic class implementing Iterable

I want to have a generic class that implements Iterable (let's call it ImplIterable) of type T that implements an Iterable interface over some class (that isn't of the generic class type); for example:

public class ImplIterable <T> implements Iterable<A> {
   private A[] tab;

   public Iterator<A> iterator() {
      return new ImplIterator();
   }

   // doesn't work - but compiles correctly.
   private class ImplIterator implements Iterator<A> {
      public boolean hasNext() { return true; }

      public A next() { return null; }

      public void remove() {}
   }
}

Where A is some class. Now, this code won't compile:

ImplIterable iable = new ImplIterable();
for (A a : iable) {
   a.aStuff();
}

But this will:

Iterable<A> = new ImplIterable();
for (A a : iable) {
   a.aStuff();
}

I don't understand why the latter doesn't compile and why can't I iterate over ImplIterable if it properly implements iterable. Am I doing something wrong/is there some workaround for this type of problems?

Upvotes: 2

Views: 1674

Answers (1)

SLaks
SLaks

Reputation: 887315

When you use a generic class without a generic parameter, all generics in that class are disabled.

Since ImplIterable is generic, and you're using it as a non-generic class, the generic parameters inside of it vanish, and it becomes an Iterable (non-generic) of Objects.

Upvotes: 3

Related Questions