2017-03-23 95 views
-1

我正在为使用泛型的集合编写一小段代码,代码如下所示。学习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 
+0

您应该指定泛型类型('名单')或“允许”所有类型的'名单<?扩展Object>'。但第二个版本没有好处,所以你应该更喜欢第一个版本。 –

+0

@PJvG他可以编译列表 list1 = new ArrayList ();'成功了,但是当Slimu回答时,您只能将null添加到带有无限通配符类型的列表中。 –

+0

@StefanWarminski对,我说错了,我的意思是他不能做'List list1 = new ArrayList ();'后面跟着'list1.add(“Zahid”);'。我会删除我的评论,因为Slimu的回答足以解释问题。 – PJvG

回答

0

当你说

新的ArrayList <>();

基本上你想要做的是实例化ArrayList。

[?]类型的WildCard字符。 wildCard [?]意味着一种特定但未知的类型。由于该类型不是编译时已知的,因此不允许修改列表。

如果您在java.util中看到arrayList的实现,那么arrayList内部有泛型,这些泛型是期望类型的。

所以当你使用wildCard“?”编译器不知道要实例化哪种类型的ArrayList。它会抛出编译时错误 “无法实例化类型ArrayList”

所以当你添加的东西。它更可能会要求您将空值添加到列表中。

为了更多地了解通配符:https://stackoverflow.com/a/12341269/7756013]