泛型和问号 [英] Generics and the question mark

查看:113
本文介绍了泛型和问号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用通用列表,但初始化方法仅返回 List
以下代码运行良好:

 列表tmpColumnList = aMethodToInitializeTheColumnList(); 
tmpColumnList.add(ANICELITTLECOLUMN);

Java指出我正在使用原始类型,我应该参数化列表。
因此,我添加了问号参数化此列表。

  List<?> tmpColumnList = aMethodToInitializeTheColumnList(); 
tmpColumnList.add(ANICELITTLECOLUMN);

问题是:现在 add(..)方法不再工作了。

我不能确保列表只包含 String s as aMethodToInitializeTheColumnList()未在我的代码中执行。



我的错误是什么?

谢谢!

解决方案

从泛型教程开始。感谢迈克尔的回答


然而,向它添加任意对象
并不安全:

 收集和LT;?> c = new ArrayList< String>(); 
c.add(new Object()); //编译时错误

由于我们不知道元素
的类型为c代表,我们不能向它添加
对象。 add()方法使用类型为E的
参数,集合的元素类型为
。当实际的
类型参数是?时,它代表
某种未知类型。 我们
传递的任何参数都必须是这个未知类型的子类型
因为我们不知道
是什么类型,所以我们不能通过
中的任何内容。唯一的例外是
null,它是每种类型的成员。



I'd like to use a generic list, but the initialization method only returns a List. The following code works well:

List tmpColumnList = aMethodToInitializeTheColumnList();
tmpColumnList.add("ANICELITTLECOLUMN");

Java accuses that I'm using a raw type and I should paramerize the list. So I added the question mark parameterize this list.

List<?> tmpColumnList = aMethodToInitializeTheColumnList();
tmpColumnList.add("ANICELITTLECOLUMN");

Problem is: Now the add(..) method doesn't work anymore.
I cannot assure that the list only contains Strings as aMethodToInitializeTheColumnList() is not implemented in my code.

What is my mistake?

Thanks!

解决方案

From the Generics Tutorial. Thanks to Michael's answer!

It isn't safe to add arbitrary objects to it however:

Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error

Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E, the element type of the collection. When the actual type parameter is ?, it stands for some unknown type. Any parameter we pass to add 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.

这篇关于泛型和问号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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