原始类型、无界通配符和在泛型中使用 Object 之间有什么区别 [英] What's the difference between raw types, unbounded wild cards and using Object in generics
问题描述
我正在阅读关于 Effective Java 中泛型的章节.
I am reading the chapter on Generics in Effective Java.
帮助我理解Set
、Set>
和Set
?
以下段落摘自书中.
快速回顾一下,Set
是一个参数化类型,表示set 可以包含任何类型的对象,Set>
是通配符类型表示只能包含某些未知对象的集合类型,而 Set
是原始类型,它选择退出泛型类型系统.
As a quick review,
Set<Object>
is a parameterized type representing a set that can contain objects of any type,Set<?>
is a wildcard type representing a set that can contain only objects of some unknown type, andSet
is a raw type, which opts out of the generic type system.
某种未知类型"是什么意思?都是Object
类型的未知类型吗?在那种情况下,Set>
和 Set
之间的具体区别是什么?
What is meant by "some unknown type"? Are all unknown types of type Object
? In that case what is the specific difference between Set<?>
and Set<Object>
?
推荐答案
- 原始类型 (
Set
) 将该类型视为根本没有泛型类型信息.请注意一个微妙的影响,不仅类型参数T
将被忽略,而且该类型的方法可能具有的所有其他类型参数也会被忽略.你可以给它添加任何值,它总是会返回Object
. Set
是一个Set
,它接受所有Object
对象(即 all 对象)并且将返回Object
类型的对象.Set<?>
是一个Set
,它接受某种特定但未知类型的所有对象,并将返回该类型的对象.由于没有关于这种类型,你不能添加任何东西到那个集合(除了null
)和你唯一知道的东西关于它返回的值是它们是Object
的一些子类型.- a raw type (
Set
) treats the type as if it had no generic type information at all. Note the subtle effect that not only will the type argumentT
be ignored, but also all other type arguments that methods of that type might have. You can add any value to it and it will always returnObject
. Set<Object>
is aSet
that accepts allObject
objects (i.e. all objects) and will return objects of typeObject
.Set<?>
is aSet
that accepts all objects of some specific, but unknown type and will return objects of that type. Since nothing is known about this type, you can't add anything to that set (except fornull
) and the only thing that you know about the values it returns is that they are some sub-type ofObject
.
这篇关于原始类型、无界通配符和在泛型中使用 Object 之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!