2

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(); 
1
  • 2
    Can you please give the return type of petstore.iterate(String)? Commented Dec 6, 2010 at 12:27

2 Answers 2

4

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(); 
Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.