简体   繁体   中英

Capturing wildcards in Java generics

From this Oracle Java tutorial:

The WildcardError example produces a capture error when compiled:

public class WildcardError {

    void foo(List<?> i) {
        i.set(0, i.get(0));
    }
}

After this error demonstration, they fix the problem by using a helper method:

public class WildcardFixed {
    void foo(List<?> i) {
        fooHelper(i);
    }

    // Helper method created so that the wildcard can be captured
    // through type inference.
    private <T> void fooHelper(List<T> l) {
        l.set(0, l.get(0));
    }
}

First, they say that the list input parameter ( i ) is seen as an Object :

In this example, the compiler processes the i input parameter as being of type Object.

Why then i.get(0) does not return an Object ? if it was already passed in as such?

Furthermore what is the point of using a <?> when then you have to use an helper method using <T> . Would not be better using directly T which can be inferred?

List<?> does mean list of object of unknown type, it's not the same as List<Object> .

Because we don't know the type of elements in the list result of i.get(0) is considered by Java as Object , and you cannot add Object to List<?> . In case as your Java could be smarter, but in more complex code with <?> wildcards it's easy to make it no type safe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM