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
?