-1

I want to create a class which accepts generics in Java, but I want to also enforce the Generic to implement the Comparable interface. This is the code

public class MyClass<Item extends Comparable> {

private Item[] items;
private Item[] copies;

public MyClass(Item[] items) {
    this.items = items;
    copies=  (Item[])new Object[items.length];

    for (int i = 0; i < items.length; ++i) {
        copies[i] = items[i];
    }
}

public static void main(String[] args) {
    Integer[] items = {23, 36, 45, 66, 25, 38, 47};

    MyClass<Integer> myClass= new MyClass<Integer>(items);
   
   }
}

As I try to run the code I get the following error:

java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to 
class [Ljava.lang.Comparable; ([Ljava.lang.Object; and [Ljava.lang.Comparable;

How should I refactor this code to get it working but also enforce it to accept only Comparable Generics and also leave the instantiating of the copies inside the constructor of the MyClass?

2
  • Are you maybe looking for this? stackoverflow.com/questions/17622820/… Commented Dec 2, 2020 at 20:12
  • 1
    Arrays and generics don’t play nice: better to use collections. Also, you’re going to want to code Item extends Comparable<Item>. Actually, T extends Comparable<T> is preferred, because Item looks like a class name, which is confusing: The java standard is the generic params are 1 letter. Commented Dec 2, 2020 at 20:37

1 Answer 1

3

Create a Comparable array instead of an Object array.

this.copies = (Item[]) new Comparable[items.length];

Demo

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

Comments

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.