I am trying to create a class that processes comparables. I boiled down to the simplest code that gives an error when I try to instantiate the class. I get a couple of compile warnings (unchecked cast) but when I run this program it throws a classcast exception. I did look at some of the other questions on this topic but didnt come across something useful.
public class GD<Item extends Comparable<Item>> {
private Item[] data;
private final int MAX_SIZE = 200;
public GD() {
data = (Item[]) new Object[MAX_SIZE];
}
public static void main(String[] args) {
GD<String> g = new GD<String>();
}
}
The problem lies here:
data = (Item[]) new Object[MAX_SIZE];
You are instantiating an array of Object
and then you try to cast it as an array of Item
, which throws an exception because Object
does not extend your Item
class, because it does not implement Comparable
. What you would like instead is:
data = new Item[MAX_SIZE];
But you can't do this because Item
is a generic type. If you want to create objects (or arrays of objects) of this type dynamically, you need to pass the Class
object to your GD class's constructor:
import java.lang.reflect.Array;
public class GD<Item extends Comparable<Item>> {
private Item[] data;
private final int MAX_SIZE = 200;
public GD(Class<Item> clazz) {
data = (Item[]) Array.newInstance(clazz, MAX_SIZE);
}
public static void main(String[] args) {
GD<String> g = new GD<String>(String.class);
}
}