&lt;?&gt;之间的区别是什么?和<?扩展对象&gt;在Java泛型? [英] What&#39;s the difference between &lt;?&gt; and &lt;? extends Object&gt; in Java Generics?

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

问题描述

我看过以前用过的通配符,意思是任何对象 - 但最近看到了使用:

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

<? extends Object>

由于所有对象都是扩展Object的,这两个用法是否同义?

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

推荐答案

<?> <?扩展对象> 是同义词,正如你所期望的那样,但是有一些泛型的情况,其中 extends Object 实际上并不是多余的。例如,< T extends Object& Foo> 会导致 T 在擦除时变为 Object ,而使用< T扩展Foo> 它会在擦除时变成 Foo 。 (如果您试图保留与使用 Object 的预泛型API的兼容性,这可能很重要。)

<?> and <? extends Object> are synonymous, as you'd expect, but 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/tutorial/extra/generics/ 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;之间的区别是什么?和<?扩展对象&gt;在Java泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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