java - 泛型类 - 当我创建一个新对象时会发生什么?
问题描述
我一直在练习通用类表示以了解它们是如何工作的,并且我有一个理论问题。
我的通用类看起来像:
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 结果相协调。
我的问题如下:
- 当我创建这些对象时,你能告诉我到底发生了什么吗?
- 有什么约定我应该如何使用这些通用表示?例如,何时使用 customCollectorC 中使用的表示,何时使用 customCollectorD 中的表示?
先感谢您。
解决方案
推荐阅读
- grafana - InfluxDB 在 TOP 函数上聚合并在 Grafana 中显示
- android - 如何设置从当前日期起 1 年的日期?
- javascript - 在Javascript中按字符串和数字属性对JSON数组进行排序
- ruby-on-rails - Ruby on Rails 撤消 where 子句
- presto - 将文本字符串拆分为 presto 中的匹配列
- c# - 如何在 C# 中赋值?
- azure - 由于证书错误,与 Azure IoT Hub 的 SSL 握手失败
- r - 从贝叶斯随机效应模型 (JAGS) 中提取预测
- php - PHP 使用查询显示来自 xml 的数据
- javascript - 如何使用 JavaScript 在 Nativescript 中更新列表项 RadListView