java - 实例化泛型类型 ArrayList<T>

标签 java generics

我是泛型的新手,读过一篇文章“参数化类型,例如 ArrayList<T>,是不可实例化的——我们无法创建它们的实例”。

完整引用,摘自 Java in a Nutshell:

A parameterized type, such as ArrayList<T>, is not instantiable - we cannot create instances of them. This is because <T> is just a type parameter - merely a place-holder for a genuine type. It is only when we provide a concrete value for the type parameter, (e.g., ArrayList<String>), that the type becomes fully formed and we can create objects of that type.

This poses a problem if the type that we want to work with is unknown at compile time. Fortunately, the Java type system is able to accommodate this concept. It does so by having an explicit concept of the unknown type which is represented as <?>.

我知道它不应该是可实例化的,因为具体(实际)类型是未知的。如果是这样,为什么下面的代码编译没有错误?

public class SampleTest {

    public static <T> List<T> getList(T... elements) {

        List<T> lst = new ArrayList<>(); // shouldn't this line return an error? 

        return lst;
    }
}

我知道我在这里对泛型的理解存在差距。有人可以指出我在这里缺少什么吗?

最佳答案

因为 T作为另一个泛型类型参数给出。

使类型可参数化是泛型的全部目的。所以调用者可以指定类型。这可以在多层中完成:调用者也可以是通用的,并让其调用者指定类型。

public static void main(String[] args)
{
  foo(7);
}

public static <T> void foo(T value)
{
  bar(value);
}

public static <U> void bar(U value)
{
  baz(value);
}

public static <V> void baz(V value)
{
  System.out.println(value.getClass().getSimpleName());
}

打印出来

Integer

A parameterized type, such as ArrayList<T>, is not instantiable

意思是:你不能创建未知T的ArrayList。它必须在编译时指定。但它可以通过另一个泛型间接完成。在你的例子中,它是另一个 T ,这将由您的通用 getList 的调用者再次指定.


通配符 <?>是不同的东西。它用于指定兼容性。 <?>是避免指定类型的语法。您可以使用 extends需要一个基类型或接口(interface)。但是,您不能使用通配符创建实例。

  List<?> list = new ArrayList<String>();
  list = new ArrayList<Integer>();

否则这是不可能的。在参数规范中使用它时最有意义,例如:

  public static int foo(List<? extends Comparable> list)
  {
     return list.get(1).compareTo(list.get(2));
  }

这本书非常令人困惑。它假设 <?>以某种方式解决了 List 的问题未知 T无法实例化。恕我直言,这是垃圾。必须指定T才能创建实例。

关于java - 实例化泛型类型 ArrayList<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52604138/

相关文章:

Java捕获图像未找到异常

c# - 如何在 C# 2.0 中使用匿名泛型委托(delegate)

java - 如何在没有 "unchecked"警告的情况下转换为(已知)泛型类型?

python - 如何将 View 方法转换为通用 ListView ?

java - 如何通过mvn包向.properties文件传递参数

java - 获取 Spring Bean 的类详细信息

java - 从 eclipse 远程调试

java - 通用示例未编译?

java - 一个具有泛型返回类型的方法怎么可能分配给该范围之外的变量?

java - 将迭代器从 JSONObject 重写为 JSONArray