Java Generics: Wildcard capture misunderstanding

前端 未结 6 616
醉话见心
醉话见心 2020-12-01 12:27

Reading the Java online tutorial I haven\'t understand anything about wildcard capture. For example:

    import java.util.List;
    public class WildcardErro         


        
6条回答
  •  Happy的楠姐
    2020-12-01 13:05

    According to Get-Put principle:

    1. If you have extends wildcard as in List, then:

      1A. You can get from the structure using Something or its superclass reference.

      void foo(List nums) {
         Number number = nums.get(0); 
         Object number = nums.get(0); // superclass reference also works.
      }
      

      1B. You cannot add anything to the structure (except null).

      void foo(List nums) {
         nums.add(1); Compile error
         nums.add(1L); Compile error
         nums.add(null); // only null is allowed.
      }
      
    2. Similarly, if you have super wildcard as in List, then:

      2A. You can add to the structure which is Something or its subclass. For eg:

      void foo(List nums) {
          nums.add(1); // Integer is a subclass of Number
          nums.add(1L); // Long is a subclass of Number
          nums.add("str"); // Compile error: String is not subclass of Number         
      }
      

      2A. You cannot get from the structure (except via Object reference). For eg:

      void foo(List nums) {
          Integer num = nums.get(0); // Compile error
          Number num = nums.get(0); // Compile error
          Object num = nums.get(0); // Only get via Object reference is allowed.        
      }
      

    Coming back to OP's question, List i is just the short representation for List i. And since it's a extends wildcard, the set operation fails.

    The final piece remaining is WHY the operation fails ? Or why the Get-Put principle in the first place? - This has to do with type safety as answered by Jon Skeet here.

提交回复
热议问题