[英]ClassCastException when using generic custom class
I was trying to construct a simple list class using generics. 我试图使用泛型构造一个简单的列表类。
However, it throws classcastexception when I was trying to print out the value. 但是,当我尝试打印该值时,它将引发classcastexception。 Is there any problem when I declare and initialize generic array?
声明和初始化通用数组时有什么问题吗?
class vector<E> {
static int MAX_LEN = 1234567;
E[] data;
int[] prv;
int to;
int size;
vector() {
data = (E[])new Object[MAX_LEN];
prv = new int[MAX_LEN];
to = -1;
size = 0;
for(int i = 0; i < MAX_LEN; ++i) {
prv[i] = -1;
}
}
void push_back(E e) {
data[size] = e;
prv[size] = to;
to = size;
++size;
}
}
public class Main {
public static void main(String[] args) throws Exception {
vector<Integer> v = new vector();
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
for(int i = v.to; i != -1; i = v.prv[i]) {
System.out.println(v.data[i]); //<- Exception here
}
}
}
There are a few things wrong with the code. 该代码有一些错误。
<>
in the line vector<Integer> v = new vector();
<>
在该行vector<Integer> v = new vector();
Object[]
to Integer[]
will never succeed Object[]
到Integer[]
永远不会成功 Ex: 例如:
Integer[] a= (Integer[]) new Object[] {};
Integer [] a =(Integer [])new Object [] {}; // this cast will never succeed
//此强制转换永远不会成功
Infact you can only cast Object[]
to Object
or Object[]
. 实际上,您只能将
Object[]
强制转换为Object
或Object[]
。
currently when you are trying to access data
in the main()
method, the cast put in by the compiler for you Integer[]
will fail at runtime. 目前,当您试图访问
data
中main()
方法,剧组投入编译器为您Integer[]
会在运行时失败。 You don't need the data
array, you just need the values from it, which you can get by adding the following method to the vector
class. 您不需要
data
数组,只需要data
数组中的值,可以通过将以下方法添加到vector
类中来获得data
数组。
E getData(int index) {
return data[index];
}
In this case, compiler will add the cast to individual elements and will provide you the correct values. 在这种情况下,编译器将强制类型转换添加到各个元素,并为您提供正确的值。
You really have two options here. 您这里确实有两个选择。 Either use
data
array of Object[]
type or create proper generic array. 使用
Object[]
类型的data
数组或创建适当的通用数组。 Here is how to create generic array. 这是创建通用数组的方法。
vector(Class<E> clazz) {
data = (E[])Array.newInstance(clazz, MAX_LEN);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.