title: Java Generics - Why is this cast unsafe
body: <p>I have read quite a bit on type erasure and explicit variance/covariance of generics but I still can't fully understand why this is an unsafe cast:</p>
  
  <pre><code>public interface TestRepository&lt;T extends ParentEntity&gt; extends JpaRepository&lt;T, String&gt; {
     List&lt;T&gt; testMethod();
  }
  </code></pre>
  
  <pre><code>
  public class TestClass() {
  
    private TestRepository testRepository;
  
    public void test() {
       List&lt;? extends ParentEntity&gt; entities = testRepository.testMethod(); //not safe
       testRepository.saveAll(entities); //safe
  
    } 
  }
  </code></pre>
  
  <p>Now I can get this to be safe by using a wildcard on the TestRepository field, but then I get a problem with the saveAll method of Jpa:</p>
  
  <pre><code>
  public class TestClass() {
  
    private TestRepository&lt;? extends ParentEntity&gt; testRepository;
  
    public void test() {
       List&lt;? extends ParentEntity&gt; entities = testRepository.testMethod(); //safe
       testRepository.saveAll(entities); //not safe
  
    } 
  }
  </code></pre>
  
  <p>What is the best way to make this work without making the TestClass generic?</p>