Java generics class cast exception -
i trying create class processes comparables. boiled down simplest code gives error when try instantiate class. couple of compile warnings (unchecked cast) when run program throws classcast exception. did @ of other questions on topic didnt come across 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 instantiating array of object , try cast array of item, throws exception because object not extend item class, because not implement comparable. instead is:
data = new item[max_size]; but can't because item generic type. if want create objects (or arrays of objects) of type dynamically, need pass class object 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); } }
Comments
Post a Comment