title: Casting generic types in Java
body: <p>I have the following custom iterator:</p>
  
  <pre><code>class PetIterator&lt;T extends Pet&gt; implements Iterator&lt;T&gt;
  </code></pre>
  
  <p>I have this class:</p>
  
  <pre><code>class Dog extends Pet
  </code></pre>
  
  <p>But the Java compiler won't allow this cast (<code>iterate</code> returns a <code>PetIterator</code>):</p>
  
  <pre><code>Iterator&lt;Dog&gt; dogs = (Iterator&lt;Dog&gt;)petstore.iterate (“dogs”);
  </code></pre>
  
  <p>How can I retrieve my Golden Retrievers, other than writing:</p>
  
  <pre><code>PetIterator dogs = petstore.iterate (“dogs”);
  ...
  Dog dog = (Dog)dogs.next();
  </code></pre>