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
Basically, when you do (E[])new Object[size], it is a lie. The object's actual runtime class is Object[], which is not a subtype of E[] for whatever E is (unless E is Object). So the cast is, theoretically, incorrect. However, this does not create any immediate problems because inside the Stack class, E is erased to its upper bound, in this case Object. So inside the Stack class, we can use elements as E[], and put E in and get E out of it, with no problem.
A problem only occurs when the (incorrect) fact that elements is type E[] is "exposed" to the outside of the class, outside of the scope of the erasure of E, into a scope where someone has a concrete type argument for E. This usually happens when someone inadvertently makes elements public, or implements a method that returns it to the outside like
E[] getElements() {
return elements;
}
Then on the outside of the class, someone has a Stack, and call this method, and expect a SomeSpecificType[], which is not what it gets.
However, your Stack class does not have such a method. So how are you "exposing" elements? The answer is that elements is protected, and is therefore "exposed" to subclasses. In this case, the subclass, MinMaxStack, extends Stack with a specific type for E, therefore, it "sees" elements as a specific type of array, which it is not.