I\'m just learning about generics in Java from a textbook, where it talks about a class GenericStack
implemented with an ArrayList
You are confusing a method's declaration with its call site (that is, where you use it). If you want to use a generic that's declared on the class, only ever need to provide the
or <>
at the call site — not the declaration. And in that regard, a constructor is declared like any other method:
public GenericStack {
public E get() { ... // correct
public put(E element) { ... // bad (see below)
public GenericStack() { ... // correct, like the get()
Redeclaring the generic (as in the put
case above) actually shadows it; the E
in put(E)
is actually a different E
than in GenericStack
, despite having the same name. This is confusing, and you should avoid doing it.