Generics Java, unbounded wildcard

落爺英雄遲暮 提交于 2019-12-04 04:33:52

问题


Hi directly from a java tutorial provided by Oracle http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html

static void filter(Collection<?> c) {
    for (Iterator<?> it = c.iterator(); it.hasNext(); )
        if (!cond(it.next()))
            it.remove();
}

I am aware of the type erasure at compilation time. And I am aware also of that a type (unbounded) is going to be substituted with Object. Being aware of that what is going to do the compiler with the unbounded wild card at compilation time? Just removing it as it was a raw type?

Thanks in advance.


回答1:


Suppose we have a generic declaration

interface Foo<T>
    T get();
    void set(T);
    void bet();

A raw type Foo is equivalent to a type declared as

interface Foo
    Object get();
    void set(Object);
    void bet();
    // all generics info are stripped

For example, in Java 5 we have List<E>, its raw version List contains the exact same method signatures as the pre-java5 List interface. Raw type is used for backward compatibility.

Raw List is pretty close to List<Object>; but very different from List<?>


An object foo of type Foo<?> has the type of

interface Foo<X>
    X get();
    void set(X);
    void bet();

for some definitive, albeit unknown, type X. Though X is unknown, we can still invoke foo.get() and foo.bet(). But we can't invoke foo.set(a) because there's no way to know whether a is of the unknown type X - unless a is null.




回答2:


This has been answered before: Java Generics - What's really in a unbounded wildcard? and Difference between an unbound wildcard and a raw type for example.

So, yes, <?> and raw types are identical (at run time).



来源:https://stackoverflow.com/questions/15568460/generics-java-unbounded-wildcard

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