0

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!

3
  • 1
    Side-note: you do know about TreeSets, right? Commented Jun 26, 2018 at 15:56
  • This is 100% runtime. The compiler put its trust in you when you declared those casts. Commented Jun 26, 2018 at 16:01
  • Yes I am aware about every other data structure but I am allowed to use array only :| , I would have solved that in 10 minutes with LinkedList , the point here is to implement a generic array sorted set Commented Jun 26, 2018 at 16:02

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

And can you explain why I have to use comparable as far is it is also extending Object
@Athl1n3 If it solves your current issue. Then you should accept it and post a new question as too much editing may mislead the question and answer. My suggestion will be posting a new question with the new problem. I would like to help you.
@Athl1n3 as you can't write a code like Comparable[] arr = (Comparable[]) new Object[5]; . It will gives you the same excpetion.
Thank you, I appreciate that and I have solved the previous mentioned issue

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.