I was trying to construct a simple list class using generics.
However, it throws classcastexception when I was trying to print out the value. 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
}
}
}