Due to the implementation of Java generics, you can't have code like this:
(由于Java泛型的实现,因此不能有以下代码:)
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
How can I implement this while maintaining type safety?
(如何在保持类型安全的同时实现此目的?)
I saw a solution on the Java forums that goes like this:
(我在Java论坛上看到了这样的解决方案:)
import java.lang.reflect.Array;
class Stack<T> {
public Stack(Class<T> clazz, int capacity) {
array = (T[])Array.newInstance(clazz, capacity);
}
private final T[] array;
}
But I really don't get what's going on.
(但是我真的不知道发生了什么。)
ask by tatsuhirosatou translate from so 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…