Java Collections using wildcard

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

    List mylist = new ArrayList();

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

}


        
                      
相关标签:
7条回答
  • 2020-12-11 04:09

    With java generics using wildcards, you are allowed the above declaration assuming you are only going to read from it.

    You aren't allowed to add/write to it, because all generic types must be stripped at compile time, and at compile time there isn't a way the compiler knows List are only strings, (it could be any object including strings!)

    You are however allowed to read from it since they are going to be at least objects. Mixing different types are not allowed in java collections to keep things clean and understandable, and this helps ensure it.

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