Ideally, we want to write
E[] elements; public Stack() { elements = new E[DEFAULT_INITIAL_CAPACITY]; }
Unfortunately, Java made a huge mistake and did not allow this. Therefore, we need workarounds.
This is a workaround.
E[] elements; public Stack() { elements = (E[]) new Object[DEFAULT_INITIAL_CAPACITY]; }
theoretically incorrect in a system like Java, because Object[] not a subtype of E[] . It happens that it works while working on modern JVMs, but we should not rely on the fact that we work forever. Well, actually, people are counting on it, and I don’t see any chance in hell that this will change. Therefore no one cares.
(correction: in fact, the §5.5 language specification specifically allows the application to run at run time, so the code is not erroneous for each specification. However, it is too hacky, it is not part of the "normal" type system, its correctness is based on some compromises that we don’t really want to study.
This second solution 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--]; }
casting from an object to E is correct, because the program logic ensures that it must be E
source share