Java泛型类强制转换异常 [英] Java generics class cast exception
问题描述
我正在尝试创建一个处理可比类的类.我归结为尝试实例化该类时给出错误的最简单代码.我收到几个编译警告(未经检查的强制转换),但是当我运行此程序时,它将引发类广播异常.我确实查看了有关该主题的其他一些问题,但是没有遇到有用的东西.
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>();
}
}
推荐答案
问题出在这里:
data = (Item[]) new Object[MAX_SIZE];
您要实例化 Object
的数组,然后尝试将其强制转换为 Item
的数组,这会引发异常,因为 Object
不会扩展您的 Item
类,因为它没有实现 Comparable
.相反,您想要的是:
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];
但是您不能这样做,因为 Item
是泛型类型.如果要动态创建此类型的对象(或对象数组),则需要将 Class
对象传递给GD类的构造函数:
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);
}
}
这篇关于Java泛型类强制转换异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!