泛型类型:通配符与原始类型的变量

Sin*_*ian 3 java oop generic-collections

考虑以下方法:

public static void listAll(LinkedList list) {

    for(Object obj : list)
        System.out.println(obj);

}
Run Code Online (Sandbox Code Playgroud)

public static void listAll(LinkedList<?> list) {

    for(Object obj : list)
        System.out.println(obj);

}
Run Code Online (Sandbox Code Playgroud)

这两种方法有什么区别?如果没有区别,为什么要使用第二个呢?

Ami*_*itG 6

<?>不允许您在列表中添加对象。请参阅下面的程序。这是我们传递给 method 的特定类型的列表<?>
具体意味着,列表是用特定类型创建的并传递给<?>方法listAll。不要与单词 specific混淆。
具体可以是任何普通对象,例如 Dog、Tiger、String、Object、HashMap、File、Integer、Long...,而且这个列表是无穷无尽的。一旦定义了包含对象的列表(在调用方法而不是在调用方法中定义
JLS则强制<?>方法执行在被调用方法中添加任何内容。 这就像在说“别碰我”。irrelevant objects<?>called-listAllspecific 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);
}
Run Code Online (Sandbox Code Playgroud)

现在让我们看看不同的场景。当我们声明特定类型(例如 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);
}
Run Code Online (Sandbox Code Playgroud)