开发者

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 retrie开发者_Python百科ve my Golden Retrievers, other than writing:

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


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();


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜