Java Collections using wildcard

前端 未结 7 1522
天命终不由人
天命终不由人 2020-12-11 03:26
public static void main(String[] args) {

    List mylist = new ArrayList();

    mylist.add(\"Java\"); // compile error

}
         


        
      
      
      
7条回答
  •  离开以前
    2020-12-11 03:57

    List, which is the same as List, fulfills the purpose of generalizing all types List, List, List, etc. (so all types with a proper type in place of the ?). Values of all of these types can be assigned to a variable of type List (which is where it differs from List!).

    In general, you cannot add a string to such a list. However, you can read Object from the list and you can add null to it. You can also calculate the length of the list, etc. These are operations that are guaranteed to work for each of these types.

    For a good introduction to wildcards, see the paper Adding Wildcards to the Java Programming Language. It is an academic paper, but still very accessible.

    提交回复
    热议问题