java - 通用类型 : wildcards vs variables of raw types

标签 java oop generic-collections

考虑以下方法:

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/

相关文章:

c# - 如何定义可以返回 DataTable 或 List <T> 的方法?

java - Hibernate查询缓存问题

java - Junit方法测试条件

java - 线程利用策略

javascript - 从 Typescript 中的基类创建子类的新实例

c# - Visual C# 2010 Express 中不完整的 System.Collections.Generic

pointers - 通用树指针 ada 的实例化

java - 在 java 中从 JComboBox 获取字符串值

php - 我怎样才能 "unset"一个已经声明的类

oop - 控制的组成和反转