首页 > 解决方案 > 泛型类 - 当我创建一个新对象时会发生什么?

问题描述

我一直在练习通用类表示以了解它们是如何工作的,并且我有一个理论问题。

我的通用类看起来像:

public class CustomCollector<T> {

  private T t;
  //getter, setter
}

我的陈述如下:

CustomCollector<ArrayList<Integer>> customCollectorA = new CustomCollector<>()
customCollectorA.setT(Arrays.asList(1, 3, 4)); 
//IntelliJ says Arrays.asList()gives back a List, 
//but an ArrayList is needed
//but Arrays.asList() gives back a List, so the types are incompatible

CustomCollector customCollectorB = new CustomCollector<ArrayList<Integer>>();
customCollectorB.setT(Arrays.asList(1, 3, 4));
//IntelliJ has no problem with it

CustomCollector customCollectorC = new CustomCollector<List<Integer>>();
customCollectorC.setT(Arrays.asList(1, 3, 4));
//IntelliJ has no problem with it    

CustomCollector<List<Integer>> customCollectorD = new CustomCollector<>();
customCollectorD.setT(Arrays.asList(1, 3, 4));
//IntelliJ has no problem with it

CustomCollector<ArrayList<Integer>> customCollectorE = new CustomCollector();
customCollectorE.setT(Arrays.asList(1, 3, 4));
//IntelliJ says it's an unchecked assignment, if I add <>, then
//the error message disappears

我想如果我想了解这里发生了什么——除非它是一个 IntelliJ 错误——我必须再次了解当我创建一个对象的新实例时发生了什么。所以这个话题本身似乎很简单,但我正在努力将我现有的知识与表示的 IntelliJ 结果相协调。

我的问题如下:

先感谢您。

标签: javagenericsconstructornew-operator

解决方案


推荐阅读