title: Why is it wrong to cast Object[] array?
body: <p>I'm very new to generic programming in Java. </p>
  
  <p>I don't understand why arrays of generic type can't be created.  <br/></p>
  
  <pre><code>T[] a = new T[size]; //why does this give an error?
  </code></pre>
  
  <p>If generic type means that the generic placeholder <code>T</code>will be replaced by a class name during run-time, what prevents us from creating an array having generic references?</p>
  
  <p>After a bit of searching, I found a workaround  <br/></p>
  
  <pre><code>T[] a = (T[])new Object[size];   //I don't get how this works?
  </code></pre>
  
  <p>Although I found a solution, I still fail to understand what prevents from creating a generic array.
  Suppose I create a function that returns an Object array.  <br/></p>
  
  <pre><code>public Object[] foo(){
          return new Object[12];
  }
  </code></pre>
  
  <p>And then make the call  <br/></p>
  
  <pre><code>String[] a = (String[])foo();
  </code></pre>
  
  <p>gives a <code>ClassCastException</code> . But why?
  Doesn't it look similar to first line of code where I cast Object array into T array?  <br></p>
  
  <pre><code> T[] a = (T[])new Object[size];
  </code></pre>
  
  <p>If this went without a glitch why didn't that? </p>