我正在为使用泛型的集合编写一小段代码,代码如下所示。学习Java泛型
import java.util.*;
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
List<?> list1 = new ArrayList<?>();
list1.add("Zahid");
list1.add(22);
System.out.print(list1.toString());
}
}
有人可以解释这段代码有什么问题。 因为它抛出以下错误。
error: unexpected type
List<?> list1 = new ArrayList<?>();
^
required: class or interface without bounds
found: ?
HelloWorld.java:11: error: no suitable method found for add(String)
list1.add("Zahid");
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; String cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; String cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
HelloWorld.java:12: error: no suitable method found for add(int)
list1.add(22);
^
method Collection.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
method List.add(CAP#1) is not applicable
(argument mismatch; int cannot be converted to CAP#1)
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
3 errors
您应该指定泛型类型('名单')或“允许”所有类型的'名单<?扩展Object>'。但第二个版本没有好处,所以你应该更喜欢第一个版本。 –
@PJvG他可以编译列表> list1 = new ArrayList >();'成功了,但是当Slimu回答时,您只能将null添加到带有无限通配符类型的列表中。 –
@StefanWarminski对,我说错了,我的意思是他不能做'List > list1 = new ArrayList >();'后面跟着'list1.add(“Zahid”);'。我会删除我的评论,因为Slimu的回答足以解释问题。 – PJvG