<?>
不允许您在列表中添加对象。请参阅下面的程序。它是我们传递给方法的特定类型的列表<?>
。
具体手段,列表以特定类型创建并传递给<?>
方法listAll
。不要与word 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);
}