Java Generics: Wildcard capture misunderstanding

前端 未结 6 611
醉话见心
醉话见心 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条回答
  •  抹茶落季
    2020-12-01 13:16

    why the compiler can't retain the assignment safe?

    The compiler doesn't know anything about the type of elements in List i, by definition of ?. Wildcard does not mean "any type;" it means "some unknown type."

    It knows that,by executing for instance, the method with an Integer List, it gets from i.get an Integer value.

    That's true, but as I said above: the compiler can only know – at compile time, remember – that i.get(0) returns an Object, which is the upper bound of ?. But there's no guarantee that ? is at runtime Object, so there is no way for the compiler to know that i.set(0, i.get(0)) is a safe call. It's like writing this:

    List fooz = /* init */;
    Object foo = fooz.get(0);
    fooz.set(0, foo); // won't compile because foo is an object, not a Foo
    

    More reading:

    • Can't add value to the Java collection with wildcard generic type
    • Java Collections using wildcard
    • Generic collection & wildcard in java
    • Generics - Cannot add to a List with unbounded wildcard
    • What is the difference betwen Collection and Collection

提交回复
热议问题