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

前端 未结 3 615
别那么骄傲
别那么骄傲 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:36

    Both the class and the constructor can be generic on their own, i.e. each has its own type parameters. For example

    class A
    {
        A(S s){}
    }
    

    To invoke the constructor with all explicit type arguments

    new A("abc");  // T=Integer, S=String
    

    Think of it like this, A is the concrete class, and A is the concrete constructor.

    Because of type inference, we can omit the type argument for the constructor

    new A("abc");  // S=String is inferred
    

    The type argument for the class can also be omitted and inferred, by "diamond" (<>) syntax

    A a = new A<>("abc");  // T=Integer is inferred, as well as S=String
    

    I wrote a (long) post on this subject - https://stackoverflow.com/a/32292707/2158288

提交回复
热议问题