title: Why does casting an ArrayList 's generic to a superclass not work?
body: <p>Can someone please explain to me why the line marked <code>//this line gives a compile error (why?)</code> in the following code sample does not work?</p>
  
  <pre><code>import java.util.ArrayList;
  
  public class GenericCastCheck {
  
      class A{
      }
  
      class B extends A{
      }
  
      public static void main(String[] args) {
  
          A aObject = new A();
          B bObject = new B();
  
          //this line works fine
          aObject = bObject;
          //this line gives a compile (expected)
          bObject = aObject;
  
          ArrayList&lt;A&gt; aList = new ArrayList&lt;A&gt;();
          ArrayList&lt;B&gt; bList = new ArrayList&lt;B&gt;();
  
          //this line gives a compile error (why?)
          aList = bList;
          //this line gives a compile error (expected)
          bList = aList;
      }
  }
  </code></pre>
  
  <p>Specifically, when we say that <code>bList</code> is of type <code>ArrayList&lt;B&gt;</code>, does it not mean that each element of it is an instance of <code>B</code>? If so, then what is the problem in casting it to <code>ArrayList&lt;A&gt;</code>, if we can cast individual instances of <code>B</code> to <code>A</code>?</p>
  
  <p>Thanks.</p>