-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?

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Siavosh
  • 2,314
  • 4
  • 26
  • 50
  • Are you maybe looking for this? https://stackoverflow.com/questions/17622820/java-generics-restrict-to-interface – RichArt Dec 02 '20 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`. Actually, `T extends Comparable` is preferred, because `Item` looks like a class name, which is confusing: The java standard is the generic params are 1 letter. – Bohemian Dec 02 '20 at 20:37

1 Answers1

3

Create a Comparable array instead of an Object array.

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

Demo

Unmitigated
  • 76,500
  • 11
  • 62
  • 80