Tony the Pony
Tony the Pony

Reputation: 41447

Casting generic types in Java

I have the following custom iterator:

class PetIterator<T extends Pet> implements Iterator<T>

I have this class:

class Dog extends Pet

But the Java compiler won't allow this cast (iterate returns a PetIterator):

Iterator<Dog> dogs = (Iterator<Dog>)petstore.iterate (“dogs”);

How can I retrieve my Golden Retrievers, other than writing:

PetIterator dogs = petstore.iterate (“dogs”);
...
Dog dog = (Dog)dogs.next();

Upvotes: 2

Views: 2929

Answers (2)

Lukas Eder
Lukas Eder

Reputation: 221275

You could rewrite your iterate(String) method to this:

class PetStore {
  <T extends Pet> PetIterator<T> iterate(Class<T> clazz);
}

Then you could use that method type-safely

PetIterator<Dog> dogs = petstore.iterate (Dog.class);
// ...
Dog dog = dogs.next();

Upvotes: 4

Bozho
Bozho

Reputation: 597382

Because PetIterator<T extends Pet> is not a PetIterator<Dog>. It can be any Pet, and then your iterator.next() will fail to cast to Dog.

Why don't you simply use class PetIterator implements Iterator<T> (which is the same T is the one in the petstore object, which I guess is also generic)

Upvotes: 3

Related Questions