Generics problem and arrays
<p>Sorry I couldnt think of a more concise title.</p>

<p>My question is why does the following piece of code work:</p>

<pre><code>public abstract class TObjectPool&lt;T&gt; {
protected Object[] availableObjects;

TObjectPool(int size){
    availableObjects = new Object[size];
}

protected class RenderElementPool extends TObjectPool&lt;RenderElement&gt;{
    @Override
    public void fill() {
        for (int i = 0; i &lt; capacity; i++) {
            availableObjects[i] = new RenderElement();   
        }
    }
}
</code></pre>

<p>when it will not work making the Object array a generic as so:</p>

<pre><code>public abstract class TObjectPool&lt;T&gt; {
protected T[] availableObjects;

TObjectPool(int size){
    availableObjects = (T[]) new Object[size];
}
</code></pre>

<p>When the availableObjects[i] = new RenderElement(); line is executed in this latter example I get a ClassCastException. I understand why it works in the first example but not why it doesn't in the second. availableObjects should be an array of RenderElement and I am trying to give it a RenderElement. What crucial bit of info am I missing?</p>

<p>Thanks for the help.</p>

<p><strong>Update...</strong></p>

<p>Thanks very much for the responses. I thought I understood but I have managed to confuse myself again:</p>

<p>If I add the function:</p>

<pre><code>public void add(int index, T object){
    availableObjects[index] = object;
}
</code></pre>

<p>to the TObjectPool class. It will happily work with the T[] array.</p>

<p>So the new TObjectPool and subclassed pool are as follows:</p>

<pre><code>public abstract class TObjectPool&lt;T&gt; {
T[] availableObjects;

TObjectPool(int size){
    availableObjects = (T[])new Object[size];
    capacity = size;
    count = capacity;
    fill();
}

public void add(int index, T object){
    availableObjects[index] = object;
}

protected class RenderElementPool extends TObjectPool&lt;RenderElement&gt;{
@Override
public void fill() {
    for (int i = 0; i &lt; capacity; i++) {
        add(i, new RenderElement()); //this works
        //availableObjects[i] = new RenderElement(); //this gives an exception          
    }
}
}
</code></pre>

<p>I know how I can get round this now after reading your responses but I am curious. Can anyone shed some light into this peculiarity?</p>

<p>Thanks again.</p>
