Why is it wrong to supply type parameter in the constructor of a generic class (Java)?

前端 未结 3 630
别那么骄傲
别那么骄傲 2021-01-15 16:00

I\'m just learning about generics in Java from a textbook, where it talks about a class GenericStack implemented with an ArrayList

3条回答
  •  长发绾君心
    2021-01-15 16:29

    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.

提交回复
热议问题