Capturing wildcards in Java generics

╄→尐↘猪︶ㄣ 提交于 2020-01-10 03:52:09

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17340474/capturing-wildcards-in-java-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!