Adam Ma
Adam Ma

Reputation: 688

Java generic class extending comparable cannot be cast to java.base/[Ljava.lang.Comparable

I am trying to get Object[] array casted to generic sorted I've implemented this part of the code

public class SortedArraySet<T extends Comparable<T>> implements Set<T>, Comparator<T> {

    T[] arr;
    int size = 5, index = 0;

    @SuppressWarnings("unchecked")
    SortedArraySet() {
        arr = (T[]) new Object[5];
        System.out.println("New set was initiated");
    }

    @Override
    public int compare(T a, T b) {

        if (a.compareTo(b) > 0)
            return 1;
        else

            return 0;
    }

When ever I run it I get the following compilation error

Exception in thread "main" java.lang.ClassCastException: java.base/[Ljava.lang.Object; cannot be cast to java.base/[Ljava.lang.Comparable; at q3.SortedArraySet.(SortedArraySet.java:12) at q3.q3main.main(q3main.java:6)

At line 6 it is stated as follows

SortedArraySet<Integer> sa = new SortedArraySet<Integer>();

The code was used to work fine before I added extends Comparable (and so compareTo) in order to sort the set

And is it possible to use Collections.sort?? I have tried but it doesn't seem to work with an array like that!

Upvotes: 0

Views: 701

Answers (1)

Amit Bera
Amit Bera

Reputation: 7235

You need to use :

arr = (T[]) new Comparable[5];

Instead of

arr = (T[]) new Object[5];

As after Type erasing T[] arr will be Comparable[] arr.So

T[] arr = (T[]) new Object[5]; 

Will become

Comparable[] arr = (Comparable[]) new Object[5];

And obviously, it will throw java.lang.ClassCastException.

Upvotes: 2

Related Questions