Sorry, I could not come up with a shorter title.
My question is why the following code snippet works:
public abstract class TObjectPool<T> { protected Object[] availableObjects; TObjectPool(int size){ availableObjects = new Object[size]; } protected class RenderElementPool extends TObjectPool<RenderElement>{ @Override public void fill() { for (int i = 0; i < capacity; i++) { availableObjects[i] = new RenderElement(); } } }
when it will not work, creating an Object array like this:
public abstract class TObjectPool<T> { protected T[] availableObjects; TObjectPool(int size){ availableObjects = (T[]) new Object[size]; }
When available objects are available [i] = new RenderElement (); the line is executed in this last example, I get a ClassCastException. I understand why it works in the first example, but not why it is not in the second. Available objects must be a RenderElement array, and I'm trying to give it a RenderElement. What important bit of information do I miss?
Thanks for the help.
Updating ...
Thanks so much for the answers. I thought I understood, but again I managed to confuse myself:
If I add a function:
public void add(int index, T object){ availableObjects[index] = object; }
for the TObjectPool class. It will work with the array T [].
So, the new TObjectPool and subclassed pool looks like this:
public abstract class TObjectPool<T> { 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<RenderElement>{ @Override public void fill() { for (int i = 0; i < capacity; i++) { add(i, new RenderElement());
I know how I can get around this now after reading your answers, but I'm curious. Can anyone shed some light on this feature?
Thanks again.