Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 360
Rollerball Avatar asked Jun 27 '13 10:06

Rollerball


1 Answers

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.

like image 118
Mateusz D. Avatar answered Oct 27 '22 08:10

Mateusz D.