0

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!

3
  • could you provide more code please? its hard to tell anything like that Commented Feb 6, 2016 at 13:56
  • List#toArray() returns Object[], not T[] (array keeps type of its elements, in this case it is Object). To sort a list, use Collections.sort(list), or provide T[] in toArray(T[] destination) Commented Feb 6, 2016 at 14:00
  • Why not just sort the list without changing it to an array using java.util.Collections: Collections.sort(list)? Commented Feb 6, 2016 at 14:37

3 Answers 3

2

toArray() returns Object[]. The type information is lost and you can't cast it back to T[]. If you want to keep the type information you can use the following. Then you give the method an predifined array which get filled. If you don't give anything - toArray will create a new Object[].

T[] elements = list.toArray(new T[list.size()]);

just filling an array (another writing style):

T[] elements = new T[list.size()];
list.toArray(elements);

or if you use Java 8:

T[] elements = list.stream().toArray(T[]::new);
Sign up to request clarification or add additional context in comments.

2 Comments

However, the complier says i cannot create generic array.
Of course, the T is only for demonstration. Outside, where you call the toArray method, you have to give a real type like String or Integer. Internally in the toArray method, the generics are used.
2

The method LinkedList.toArray() creates a new array of the type Object[]. It does not create a new array of the type T[]. This is important, because even though the array only contains instances of T, you cannot assign the array to a variable of the type T[], because the array itself has the type Object[]. You can reproduce this error with the following code:

String[] array = (String[]) new Object[0];

If I understand you correctly, you want to convert the list into an array to be able to implement your own search function. Given a List<T>, that contains elements of the type T you want to convert this list into an array of the type T[]. However, you cannot simply call new T[list.size()], since Java looses the generic type information at compile time. To create the correctly typed array, you need to use the reflection method Array.newInstance().

Here is an example:

@SuppressWarnings("unchecked")
private <T extends Comparable<T>> void sort(List<T> list, Class<T> clazz) {
    T[] array = list.toArray((T[]) Array.newInstance(clazz, list.size()));
    // sort array and write result to the list
}

And here the usage:

    List<String> list = new LinkedList<String>();
    // populate the list
    sort(list, String.class);
    System.out.println(list); // -> the sorted list

2 Comments

Thanks for the extra work. I will do some further research in these stuff
Always happy to help. The keyword is type erasure.
1

You should use T[] toArray(new T[list.size()]) instead. No need to cast.

3 Comments

@BenyBosko because T[] is "array of Ts", not "array of Objects". Type erasure isn't applied.
But i thought the underlying type is T and not Object in the returned array! Sorry, it is not clear.
@BenyBosko this method appeared far before generics were introduced, when List was just List. Now it is impossible to change return type to T[] because of backward compatibility.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.