Type arguments in Java

前端 未结 1 1078
不思量自难忘°
不思量自难忘° 2021-01-23 15:14

Is there any difference between the following two declarations?

public> List search (C condition)

public List

        
1条回答
  •  情话喂你
    2021-01-23 15:44

    No, there's no useful difference. The distinction could be simplified to the following.

     void m(T object)
    
    void m(Object object)
    

    Although with the first one could call this.m(42) and it wouldn't compile - but there's no value to that.

    The value of a generic method comes when there is some relationship expressed by its type parameters, for example:

     T giveItBackToMe(T object) {
        return object;
    }
    
    ...
    
    String s = giveItBackToMe("asdf");
    Integer i = giveItBackToMe(42);
    

    Or:

     void listCopy(List from, List to) {
        to.addAll(from);
    }
    
    ...
    
    List ints = Arrays.asList(1, 2, 3);
    List nums = new ArrayList<>();
    listCopy(ints, nums);
    

    0 讨论(0)
提交回复
热议问题