-1

For a project of mine i'm trying to convert a given Collection to an array

I currently have this:

public class InsertionSorter< T extends Comparable<T>> {
    private T[] array;

    @SuppressWarnings("unchecked")
    public InsertionSorter(){
        array = (T[]) new Object[0];
    }
}

This gives me the following error:

java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to java.base/[Ljava.lang.Comparable;

Is there a solution for this?

And after i converted it to an array i want to to sort it and return it back as an collection. I do this as following:

collection.clear();
collection.addAll(Arrays.asList(sort(array)));
return collection;

The sort method is a method which sorts an array and returns an array of type T.

Kevin Tabak
  • 19
  • 1
  • 1
  • 7

1 Answers1

0

Your typedefinition T claims that instances will be at least Comparable, but then you try to assign an array of Object, which is not Comparable, thus resulting in a ClassCastException.

M. le Rutte
  • 3,525
  • 3
  • 18
  • 31