Ideally we want to write
E[] elements;
public Stack()
{
elements = new E[DEFAULT_INITIAL_CAPACITY];
}
Unfortunately, Java made a colossal mistake and didn't allow that. So we need workarounds.
This workaround
E[] elements;
public Stack()
{
elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY];
}
is theoretically wrong in the Java type system, since an Object[]
is not a subtype of E[]
. It happens to work at runtime on today's JVMs, however, we are not supposed to count on that to work forever. Well, actually, people do count on that, and I don't see any chance in hell that it'll change. So nobody cares.
(correction: actually the language spec §5.5 specifically allows the cast to work at runtime, therefore the code is not wrong per spec. nevertheless, it is too hackish, it is not part of "normal" type system, its correctness is based on some compromises that we dont' really want to learn.)
That 2nd workaround is correct, both practically and theoretically
Object[] elements;
public Stack()
{
elements = new Object[DEFAULT_INITIAL_CAPACITY];
}
public push(E e)
{
...
elements[size++] = e;
}
public E pop()
{
...
E result = (E)element[size--];
}
the casting from Object to E is correct, since the program logic ensures that it must be an E
.