I have a LinkedList<T> which contains Object toArray() method:
public Object[] toArray()
{
Object[] array = new Object[size];
int c=0;
for(Node<T> i = first;i != null;i=i.next)
{
array[c++] = i.data;
}
return array;
}
I would like to sort my LinkedList with a generic method: <T extends Comparable> void sort (List<T> list). To sort lists, i must represent them as array in this method:
T[] elements = (T[])list.toArray();`
However, i get ClassCastException at this line and i don't know why. Since the generic type of the method equivalent to the element's runtime type in the returned array, this cast is not a lie!
List#toArray()returnsObject[], notT[](array keeps type of its elements, in this case it isObject). To sort a list, useCollections.sort(list), or provideT[]intoArray(T[] destination)Collections.sort(list)?