Difference between ? (wildcard) and Type Parameter in Java

后端 未结 3 918
滥情空心
滥情空心 2020-12-13 04:38

Can somebody explain me what the difference is between these two methods? Are they same? They do look same to me in terms of what they solve. If they are same, why need

3条回答
  •  情歌与酒
    2020-12-13 05:00

    They are the same in that they accept the same parameter types.

    However, identifying the type with T (or whatever) lets you refer to the type elsewhere.

    Edit: Examples:

    Your unbounded examples do not make full use of the capabilities of parameterized types. You have:

    public static  void printList(List list) {
        for (Object elem : list)
            System.out.println(elem + " ");
        System.out.println();
    }
    

    And that's sufficient for that example of printing string representations, but consider this (very contrived, and no error handling):

    public static  T getSecondItem (List list) {
        T item = list.get(1);
        return item;
    }
    

    The return type is T, which allows you to safely do things like this, with compile time type-checking:

    class MyClass {
        public void myMethod () { }
    }
    
    void somewhere () {
        List items = ...;
        getSecondItem(items).myMethod();
    }
    

    A named type also lets you share the same type constraint in multiple places, e.g.:

    public  int compareLists (List a, List b) {
        ...
    }
    

    If you did not name the type, you could not specify the constraint that a and b are the same list type (you could use List for more flexibility).

    You also asked "Why do I need ??". The real answer is: You don't. It's mostly for aesthetics, I suppose. Java strives to be a precise and clutter-free language. There are many situations where you simply don't care what type you are referring to. In those cases, you may use ? without cluttering code with unused type parameter declarations.

提交回复
热议问题