考虑以下方法:
public static void listAll(LinkedList list) {
for(Object obj : list)
System.out.println(obj);
}
和
public static void listAll(LinkedList<?> list) {
for(Object obj : list)
System.out.println(obj);
}
这两种方法有什么区别?如果没有区别,为什么要用第二个呢?
最佳答案
<?>
不允许您在列表中添加对象。请参阅下面的程序。这是我们传递给方法的特定类型的列表 <?>
.
具体方法,列表是用特定类型创建的,并传递给<?>
方法 listAll
.不要与词 specific
混淆.
Specific 可以是任何普通对象,例如 Dog、Tiger、String、Object、HashMap、File、Integer、Long...,列表是无止境的。
JLS
部队 <?>
不执行添加任何方法irrelevant objects
在调用 <?>
定义(在调用方法中定义而不是在called-listAll
中定义) 包含specific type
的列表后的方法的对象。
就像<?>
说“别碰我”。
public static void listAll(LinkedList list)
{
list.add(new String()); //works fine
for(Object obj : list)
System.out.println(obj);
}
public static void listAll(LinkedList<?> list)
{
list.add(new String()); //compile time error. Only 'null' is allowed.
for(Object obj : list)
System.out.println(obj);
}
现在让我们看看不同的场景。当我们声明特定类型时会发生什么,比如 Dog、Tiger、Object、String ..... 任何东西。让我们将方法更改为 specific type
.
public static void listAll(LinkedList<String> list)// It is now specific type, 'String'
{
list.add(new String());//works fine. Compile time it knows that 'list' has 'String'
for(Object obj : list)
System.out.println(obj);
}
关于java - 通用类型 : wildcards vs variables of raw types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15517611/