title: Casting generics list in Java
body: <p>I found a weird situation when casting generics. I run this code:</p>
  
  <pre><code>class A { }
  
  class B { }
  
  public class Program {
  
      @SuppressWarnings("unchecked")
      public static void main(String[] args) {
          List&lt;A&gt; listA = new ArrayList&lt;A&gt;();
          List&lt;?&gt; list = listA;
          ((List&lt;B&gt;)list).add(new B());
  
          for (Object item : listA) {
              System.out.println(item.toString());
          }
      }
  }
  </code></pre>
  
  <p>It compiles very well (only with warning but without error) and run without any exception and the output was:</p>
  
  <blockquote>
    <p>B@88140ed</p>
  </blockquote>
  
  <p>How did I do that? I mean why Java allow me to do such thing? 
  I added an instance of <code>B</code> class to list of <code>A</code>s?</p>
  
  <p>It is very bad behaviour of generics. Why it is happening?</p>
  
  <p>BTW, I tried it with Java 7.</p>
  
  <p><strong>EDIT:</strong><br>
  What surprised me is that Java only notify the problem with warning that every programmer can ignore it. I know that <code>SuppressWarnings</code> is bad idea, but why Java didn't denied such behavior with error or exception?  </p>
  
  <p>In addition, this warning showed always, if you think that your casting is correct you have no choice but to ignore it. But if you think that is good casting and ignore it but it isn't?</p>