Multiple wildcards on a generic methods makes Java compiler (and me!) very confused

后端 未结 3 1210
[愿得一人]
[愿得一人] 2020-11-22 16:03

Let\'s first consider a simple scenario (see complete source on ideone.com):

import java.util.*;

public class TwoListsOfUnknowns {
    static void doNothing         


        
3条回答
  •  猫巷女王i
    2020-11-22 16:54

    As Appendix B indicates, this has nothing to do with multiple wildcards, but rather, misunderstanding what List> really means.

    Let's first remind ourselves what it means that Java generics is invariant:

    1. An Integer is a Number
    2. A List is NOT a List
    3. A List IS a List

    We now simply apply the same argument to our nested list situation (see appendix for more details):

    1. A List is (captureable by) a List
    2. A List> is NOT (captureable by) a List>
    3. A List> IS (captureable by) a List>

    With this understanding, all of the snippets in the question can be explained. The confusion arises in (falsely) believing that a type like List> can capture types like List>, List>, etc. This is NOT true.

    That is, a List>:

    • is NOT a list whose elements are lists of some one unknown type.
      • ... that would be a List>
    • Instead, it's a list whose elements are lists of ANY type.

    Snippets

    Here's a snippet to illustrate the above points:

    List> lolAny = new ArrayList>();
    
    lolAny.add(new ArrayList());
    lolAny.add(new ArrayList());
    
    // lolAny = new ArrayList>(); // DOES NOT COMPILE!!
    
    List> lolSome;
    
    lolSome = new ArrayList>();
    lolSome = new ArrayList>();
    

    More snippets

    Here's yet another example with bounded nested wildcard:

    List> lolAnyNum = new ArrayList>();
        
    lolAnyNum.add(new ArrayList());
    lolAnyNum.add(new ArrayList());
    // lolAnyNum.add(new ArrayList());     // DOES NOT COMPILE!!
    
    // lolAnyNum = new ArrayList>(); // DOES NOT COMPILE!!
    
    List> lolSomeNum;
        
    lolSomeNum = new ArrayList>();
    lolSomeNum = new ArrayList>();
    // lolSomeNum = new ArrayList>(); // DOES NOT COMPILE!!
    

    Back to the question

    To go back to the snippets in the question, the following behaves as expected (as seen on ideone.com):

    public class LOLUnknowns1d {
        static void nowDefinitelyIllegal(List> lol, List list) {
            lol.add(list); // DOES NOT COMPILE!!!
                // The method add(capture#1-of ? extends List) in the
                // type List> is not 
                // applicable for the arguments (List)
        }
        public static void main(String[] args) {
            List list = null;
            List> lolString = null;
            List> lolInteger = null;
    
            // these casts are valid
            nowDefinitelyIllegal(lolString, list);
            nowDefinitelyIllegal(lolInteger, list);
        }
    }
    
    

    lol.add(list); is illegal because we may have a List> lol and a List list. In fact, if we comment out the offending statement, the code compiles and that's exactly what we have with the first invocation in main.

    All of the probablyIllegal methods in the question, aren't illegal. They are all perfectly legal and typesafe. There is absolutely no bug in the compiler. It is doing exactly what it's supposed to do.


    References

    • Angelika Langer's Java Generics FAQ
      • Which super-subtype relationships exist among instantiations of generic types?
      • Can I create an object whose type is a wildcard parameterized type?
    • JLS 5.1.10 Capture Conversion

    Related questions

    • Any simple way to explain why I cannot do List animals = new ArrayList()?
    • Java nested wildcard generic won’t compile

    Appendix: The rules of capture conversion

    (This was brought up in the first revision of the answer; it's a worthy supplement to the type invariant argument.)

    5.1.10 Capture Conversion

    Let G name a generic type declaration with n formal type parameters A1…An with corresponding bounds U1…Un. There exists a capture conversion from G1…Tn> to G1…Sn>, where, for 1 <= i <= n:

    1. If Ti is a wildcard type argument of the form ? then …
    2. If Ti is a wildcard type argument of the form ? extends Bi, then …
    3. If Ti is a wildcard type argument of the form ? super Bi, then …
    4. Otherwise, Si = Ti.

    Capture conversion is not applied recursively.

    This section can be confusing, especially with regards to the non-recursive application of the capture conversion (hereby CC), but the key is that not all ? can CC; it depends on where it appears. There is no recursive application in rule 4, but when rules 2 or 3 applies, then the respective Bi may itself be the result of a CC.

    Let's work through a few simple examples:

    • List can CC List
      • The ? can CC by rule 1
    • List can CC List
      • The ? can CC by rule 2
      • In applying rule 2, Bi is simply Number
    • List can NOT CC List
      • The ? can CC by rule 2, but compile time error occurs due to incompatible types

    Now let's try some nesting:

    • List> can NOT CC List>
      • Rule 4 applies, and CC is not recursive, so the ? can NOT CC
    • List> can CC List>
      • The first ? can CC by rule 2
      • In applying rule 2, Bi is now a List, which can CC List
      • Both ? can CC
    • List> can CC List>
      • The first ? can CC by rule 2
      • In applying rule 2, Bi is now a List, which can CC List
      • Both ? can CC
    • List> can NOT CC List>
      • The first ? can CC by rule 2
      • In applying rule 2, Bi is now a List, which can CC, but gives a compile time error when applied to List
      • Both ? can CC

    To further illustrate why some ? can CC and others can't, consider the following rule: you can NOT directly instantiate a wildcard type. That is, the following gives a compile time error:

        // WildSnippet1
        new HashMap();         // DOES NOT COMPILE!!!
        new HashMap, ?>();  // DOES NOT COMPILE!!!
        new HashMap>();   // DOES NOT COMPILE!!!
    

    However, the following compiles just fine:

        // WildSnippet2
        new HashMap,Set>();            // compiles fine!
        new HashMap, Map>>(); // compiles fine!
    

    The reason WildSnippet2 compiles is because, as explained above, none of the ? can CC. In WildSnippet1, either the K or the V (or both) of the HashMap can CC, which makes the direct instantiation through new illegal.

    提交回复
    热议问题