Java Collections using wildcard

前端 未结 7 1574
天命终不由人
天命终不由人 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:47

    The point of bounded wildcard types is their use in method signatures to increase API flexibility. If, for example, you implement a generic Stack, you could provide a method to push a number of elements to the stack like so:

    public void pushAll(Iterable elements) {
        for(E element : elements){
           push(e);
        }
    }
    

    Compared to a pushAll(Iterable elements) signature without a wildcard, this has the advantage that it allows collections of subtypes of E to be passed to the method - normally that would not be allowed because an Iterable is, somewhat counterintuitively, not a subclass of Iterable.

    提交回复
    热议问题