为什么下列方法不会产生潜在的堆污染? [英] Why doesn't the following method produce potential heap pollution?
问题描述
Java 7
我写了:
public static <E extends Enum<E>> List<SelectItem> getSelectItemList(Enum<E>... es){
List<SelectItem> items = new ArrayList<SelectItem>();
for(Enum<E> e : es){
items.add(new SelectItem(e, e.toString()));
}
return items;
}
这个方法编译没有警告。为什么?我预计这种使用通用类型(实际上是一个数组)的变量生成
and this method compiled with no warning. Why? I expected that such using of varargs of a generic type (which is actually an array) produces
通过varargs参数es $产生潜在的堆污染c $ c>
你不能解释吗?
推荐答案
不可重复类型的变量倾向于这样工作。 枚举< E - 代替; ...
在运行时被有效地评估为枚举[]
。在这一点上,您无法确定哪些参考可能会进入数组。
Varargs of non - reifiable types tend to work like this. Enum<E> ...
is effectively evaluated as Enum[]
at runtime. At this point you can't be sure what references might get into the array.
更多信息: https://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html
枚举
基本类型实际上会给你一些类型 - 安全,即使在编译时,所以我想这就是为什么你是安全的。
The Enum
base type will actually give you some type - safety, even in compile time, so I guess this is why you are safe.
这篇关于为什么下列方法不会产生潜在的堆污染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!