Java:如何对待通用异构容器?
在处理异构容器(即带有字符串、整数等的数据库游标)时,什么(以及为什么)是更好的方法:
Vector<?>
或者
Vector<Object>
您可以用 Vector 替换任何其他 Collection,这只是示例。
While dealing with heterogeneous containers (i.e. database cursor with strings, ints etc.), what (and why) is better approach:
Vector<?>
or
Vector<Object>
You can substitute Vector for any other Collection, that's just example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不太确定你在比较什么。尝试创建类似的向量
会出现错误,
无法实例化类型 Vector
如果在参数列表中使用
(不使用 super关键字),这意味着您无法将任何内容插入集合中。如果您使用
I'm not exactly sure what you're comparing. Trying to create a vector like
gets an error,
Cannot instantiate the type Vector<?>
If you use
<?>
in a parameter list (without using the super keyword) that means you can't insert anything into the collection. If you use<Object>
then you can insert and remove things.使用
Vector
use
Vector<Object>
. The?
wildcard should be used when you are writing code that does not know what is the generic type of the collection. You cannot create anew Vector<?>
so why hold it as such. You know you want a collection that will hold anyObject
so declare it as such.Vector
Vector
是未知类型的同质容器。Vector<Object>
is a heterogeneous container.Vector<?>
is a homogenous container of unknown type.Collection
是所有类型Collection
的超类型,包括Collection
使用
Collection
允许您获取集合的内容,该内容始终至少是一个对象。但正如 Nathan 所说,使用
Collection
将不允许您添加或删除元素。因为要添加或删除的任何参数传递都必须是此未知类型的子类型 ()。因为我们不知道那是什么类型,所以我们不能传递任何东西。唯一的例外是 null,它是每个类型的成员。
因此,如果您只需要查阅
Collection
的内容,则可以使用通配符类型,但如果您想添加/删除某些元素,则必须使用Collection
Collection<?>
is the super type of all kind ofCollection
includingCollection<?>
Using
Collection<?>
allows you to get the content of the collection which will always be at least an Object.But as Nathan said using
Collection<?>
will not allows you to add or remove elements. Because any parameter pass to add or remove would have to be a subtype of this unknown type (<?>
). Since we don’t know what type that is, we cannot pass anything in. The sole exception is null, which is a member of every type.So if you only need to consult the content of the
Collection
you can use wilcard type but if you want to add/remove some elements you have to useCollection<Object>
.