简体   繁体   English

为什么以下方法不会产生潜在的堆污染?

[英]Why doesn't the following method produce potential heap pollution?

Java 7 Java 7

I wrote this: 我写了这个:

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(实际上是一个数组)会产生

Potential heap pollution via varargs parameter es

Couldn't you explain it? 你不能解释一下吗?

Varargs of non - reifiable types tend to work like this. 不可恢复类型的Varargs倾向于这样工作。 Enum<E> ... is effectively evaluated as Enum[] at runtime. Enum<E> ...在运行时被有效地评估为Enum[] At this point you can't be sure what references might get into the array. 此时,您无法确定哪些引用可能会进入数组。

More info here: https://docs.oracle.com/javase/tutorial/java/generics/nonReifiableVarargsType.html 更多信息: 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. 即使在编译时, Enum基类型实际上会给你一些类型 - 安全性,所以我想这就是你安全的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM