<?> 和有什么区别?和 <?扩展对象>在 Java 泛型中? [英] What's the difference between <?> and <? extends Object> in Java Generics?

查看:30
本文介绍了<?> 和有什么区别?和 <?扩展对象>在 Java 泛型中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我曾见过通配符表示任何对象 - 但最近看到了使用:

I've seen the wildcard used before to mean any object - but recently saw a use of:

<? extends Object>

既然所有的对象都扩展了对象,那么这两种用法是同义词吗?

Since all objects extend Object, are these two usages synonymous?

推荐答案

是同义词,正如您所期望的那样.

<?> and <? extends Object> are synonymous, as you'd expect.

在某些情况下,extends Object 实际上并不是多余的泛型.例如,<T extends Object &Foo> 将导致 T 在擦除时变成 Object,而使用 它将变成 Foo 下擦除.(如果您试图保持与使用 Object 的前泛型 API 的兼容性,这可能很重要.)

There are a few cases with generics where extends Object is not actually redundant. For example, <T extends Object & Foo> will cause T to become Object under erasure, whereas with <T extends Foo> it will become Foo under erasure. (This can matter if you're trying to retain compatibility with a pre-generics API that used Object.)

来源:http://download.oracle.com/javase/教程/额外/泛型/convert.html;它解释了为什么 JDK 的 java.util.Collections 类有一个带有这个签名的方法:

Source: http://download.oracle.com/javase/tutorial/extra/generics/convert.html; it explains why the JDK's java.util.Collections class has a method with this signature:

public static <T extends Object & Comparable<? super T>> T max(
    Collection<? extends T> coll
)

这篇关于&lt;?&gt; 和有什么区别?和 &lt;?扩展对象>在 Java 泛型中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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