title: Generic Type cast
body: <p>I have the following class (simplified but still a working example):</p>
  
  <pre><code>class Test&lt;T&gt; {
      List&lt;T&gt; l = new ArrayList&lt;&gt;();
  
      public Test() {
      }
  
      public void add(Object o) {
          l.add((T)o);
      }
  }
  </code></pre>
  
  <p>And the test code:</p>
  
  <pre><code>Test&lt;Double&gt; t = new Test&lt;&gt;();
  t.add(1);
  t.add(1.2);
  t.add(-5.6e-2);
  t.add("hello");
  </code></pre>
  
  <p>Everything is working fine, and that's not what I was expecting. Shouldn't the <code>add</code> method throw a <code>ClassCastException</code>? If I add a <code>get</code> method that's more or less the same thing:</p>
  
  <pre><code>    public T get(int i) {
          return l.get(i);
      }
  .../...
  t.get(1);             // OK.
  t.get(3);             // OK (?)
  Double d = t.get(3);  // throws ClassCastException
  </code></pre>
  
  <p>Why is it only on variable assignment that the exception is thrown? How can I enforce type consistency if the <code>(T)</code> cast doesn't work?</p>