本文介绍了原始类型,无界通配符和使用泛型中的对象有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在阅读有效Java中泛型的一章。
帮我理解 Set , Set < / code>和 Set< Object> ?
以下段落摘自本书。
某种未知类型的含义是什么?是所有未知类型的类型 Object ?在那种情况下, Set < / code>和 Set< Object> ?
解决方案
- 原始类型( Set )将类型就好像它根本没有通用类型信息一样。请注意,不仅可以忽略类型参数 T ,而且可以使用该类型的方法可能具有的所有其他类型参数。您可以为其添加任何值,并且它将始终返回 Object 。
- Set< Object> 是一个 Set ,它接受所有的 Object 对象(即 all )并将返回 Object 类型的对象。
- Set < / code >是一个 Set ,它接受一些特定的但未知的类型的所有对象,并且将返回该类型的对象。由于 关于此类型是已知的,因此您无法将 任何内容添加到该集合中(除 null )和你知道它返回的唯一值是它们是 Object 的一个子类型。
I am reading the chapter on Generics in Effective Java.
Help me understand difference between Set, Set<?> and Set<Object>?
The following paragraph is taken from the book.
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>?
解决方案
- 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 argument T 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 return Object.
- Set<Object> is a Set that accepts all Object objects (i.e. all objects) and will return objects of type Object.
- Set<?> is a Set 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 for null) and the only thing that you know about the values it returns is that they are some sub-type of Object.
这篇关于原始类型,无界通配符和使用泛型中的对象有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!