泛型Java,无界通配符 [英] Generics Java, unbounded wildcard

查看:122
本文介绍了泛型Java,无界通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您可以直接从Oracle提供的java教程 http:// docs .oracle.com / javase / tutorial / collections / interfaces / collection.html

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();
}

我知道编译时的类型擦除。而且我也知道一个类型(无界)将被替换为Object。在编译时意识到编译器和无界通配符会做什么?只是删除它,因为它是一个原始类型?

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.

推荐答案

假设我们有一个泛型声明

Suppose we have a generic declaration

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

原始类型 Foo 相当于一个类型声明为

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

例如,在Java 5中,我们有 List< E> ,它的原始版本 List包含了与java5之前完全相同的方法签名列表界面。原始类型用于向后兼容。

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 非常接近 List<对象> ;但与 List <?>< / code>

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

Foo <?> 类型的 foo 具有

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

对于一些确定的,尽管未知的类型X.尽管X是未知的,我们仍然可以调用 foo.get() foo.bet()。但是我们不能调用 foo.set(a),因为无法知道 a 是未知的键入 X - 除非 a null

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.

这篇关于泛型Java,无界通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆