java - 通用方法调用

标签 java generics

我一直在尝试使用 Generic,很快我就遇到了一些我无法解释的事情。
例如:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        //We cannot create List<?> l = new ArrayList<?>();
        List<?> l = MagicClass.factory();
    }
    static class MagicClass {
        public static <T> List<T> factory() {
            return new ArrayList<T>();
        }
    }
}

我不明白<T>可以是显式类型参数,而这个

<?>

未定义。

最佳答案

使用通配符实例化泛型会产生编译错误,因为通配符表示任何类型,而实例化的 ArrayList应该有一个具体的类型。通配符可用于变量或参数类型,但不能用于创建泛型类型的实例。

this tutorial page 中也提到了这一点:

In generic code, the question mark (?), called the wildcard, represents an unknown type. The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable; sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.

另一方面,在factory方法,T是将由编译器推断的类型参数,并且由于 List<?>表示任何类型,它被编译器接受。

关于java - 通用方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27877584/

相关文章:

java - 扩展 CompletableFuture 时类型不匹配

c# - Entity Framework 动态 Where 子句

C#泛型问题

java - Java 中的泛型工厂

java - 使用 Apache POI 追加 Excel 文件

java - 重新排序 int 数字中的数字以获得最小值

java - C++ 等价于使用 <T extends Class> 作为 java 参数/返回类型

java - 这是java泛型吗?这怎么可能工作?

java - 学习 Java 字节码和 JVM

java - kotlin项目无法在gradle中构建