Generics Java, unbounded wildcard

2019-02-25 06:46发布

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.

2条回答
对你真心纯属浪费
2楼-- · 2019-02-25 07:33

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.

查看更多
聊天终结者
3楼-- · 2019-02-25 07:45

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).

查看更多
登录 后发表回答