为什么以下成功将 ArrayList 发送到 List?
我知道类型擦除,并且所有通用列表基本上都是运行时的 Object 列表。
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>(Arrays.asList(3,4,5));
List<Double> doubles = new ArrayList<>(Arrays.asList(3.1,4.1,5.1));
duplicateFirstElement(ints);
duplicateFirstElement(doubles); // why no error ?
}
static <Integer> void duplicateFirstElement(List<Integer> list) {
Integer first = list.get(0);
list.add(first); // Would not work with ?
}
究竟是什么
static <Integer> void functionName()
以我的 C++ 经验,起初我认为这是模板函数专业化。
我是否只是用 Integer 这个词隐藏了参数类型名称(例如 T),而这实际上是一个与 Integer 无关的通用函数?如果是这样,为什么允许使用名为“整数”的类型参数进行隐藏?