I have written a generic class and below is the constructor of the class. I want to do something like this as written in line
elements = (E[])new Object[siz
Here is the most-minimal code necessary to reproduce your exception.
class Stack {
protected E[] elements = (E[])new Object[1];
}
class IntStack extends Stack {
void push(Integer i) {
// subtly accessing elements as Integer[] which it's not
elements[0] = i;
}
}
Java generics are implemented with type erasure so after compilation, this code translates to something like this:
class Stack {
protected Object[] elements = new Object[1];
}
class IntStack extends Stack {
void push(Integer i) {
// throws ClassCastException
((Integer[])elements)[0] = i;
}
}
Clearly a new Object[]
is not an Integer[]
. Notice how the cast gets moved to somewhere you did not explicitly put it. This is why (E[])new Object[size]
was an unchecked cast and displayed a warning.
Instead, you should use Object[]
and perform the unchecked cast only when you need to return an element to the outside world.
class Stack {
private Object[] elements;
private int size;
Stack(int len) {
elements = new Object[len];
}
void push(E e) {
elements[size] = e;
size++;
}
E pop() {
@SuppressWarnings("unchecked");
E e = (E)elements[size - 1];
size--;
return e;
}
}