I have a Stack class implemented using Array, and I get an unchecked warning in my constructor. It seems unwarranted because any type is a subtype of Object hence an array type of Object should be able to be downcasted to ? or am I missing something?
public class StackArray<E> implements Stack<E> {
int tos;
E[] stack;
public StackArray() {
this(10);
} // default size is 10
public StackArray(int maxdepth) {
tos = 0;
/*
type safety check, doesn't know if Object and E array are fine together
Casting a raw-type to a parameterized type gives unchecked conversion warning
https://docs.oracle.com/javase/tutorial/java/generics/rawTypes.html
*/
stack = (E[]) new Object[maxdepth]; //unchecked warning here
// Cannot create instances of type parameters
// https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createObjects
// stack = new E[maxdepth]; // won't compile, type E cannot be instantiated directly
}
@Override
public void push(E element) {
stack[tos++] = element;
}
@Override
public E pop() {
return tos>0 ? stack[--tos] : null;
}
}