I would like to understand the relationship between generics and arrays finally, so i will provide an example which is inconsisent for me, based on an ArrayList<T> :
Object[] elementData = new Object[size];
This is where elements of the generic list are stored.
public void add(T element){ elementData[size++] = element; }
public T get(int index) { return (T)elementData[index] }
Completely works. I can get out the underlying <T> objects, however the array which contains the references to these objects is Object.
In contrast to this:
public Object[] toArray()
{
Object[] result = new Object[size];
for(int i = 0;i<size;i++)
{
result[i] = elementData[i];
}
return result;
}
I cannot cast the elements in the returned array to their real type, however the whole set up is the same: an Object array which contains references to <T> objects. I got ClassCastException error, when trying to cast the elements to their real type.
T[]RealType[] foo = (RealType[]) list.toArray()? Note thatList<T>is a "generic" variant ofList<Object>, butT[]is an entirely different class thanObject[](That's why there is a secondtoArraymethod)<T>is that the array's typeObjectis distinct from the elements type<T>?toArray().