由于Java泛型的实现,你不能有这样的代码:
public class GenSet<E> {
private E a[];
public GenSet() {
a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
}
}
如何在保持类型安全的同时实现这一点?
我在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;
}
但我真的不明白这是怎么回事。
您不需要将Class参数传递给构造函数。
试试这个。
public class GenSet<T> {
private final T[] array;
@SafeVarargs
public GenSet(int capacity, T... dummy) {
if (dummy.length > 0)
throw new IllegalArgumentException(
"Do not provide values for dummy argument.");
this.array = Arrays.copyOf(dummy, capacity);
}
@Override
public String toString() {
return "GenSet of " + array.getClass().getComponentType().getName()
+ "[" + array.length + "]";
}
}
and
GenSet<Integer> intSet = new GenSet<>(3);
System.out.println(intSet);
System.out.println(new GenSet<String>(2));
结果:
GenSet of java.lang.Integer[3]
GenSet of java.lang.String[2]
如果你真的想包装一个固定大小的通用数组,你将有一个方法来添加数据到该数组,因此你可以正确地初始化数组,这样做:
import java.lang.reflect.Array;
class Stack<T> {
private T[] array = null;
private final int capacity = 10; // fixed or pass it in the constructor
private int pos = 0;
public void push(T value) {
if (value == null)
throw new IllegalArgumentException("Stack does not accept nulls");
if (array == null)
array = (T[]) Array.newInstance(value.getClass(), capacity);
// put logic: e.g.
if(pos == capacity)
throw new IllegalStateException("push on full stack");
array[pos++] = value;
}
public T pop() throws IllegalStateException {
if (pos == 0)
throw new IllegalStateException("pop on empty stack");
return array[--pos];
}
}
在这种情况下,您使用java.lang.reflect.Array.newInstance来创建数组,它将不是Object[],而是一个真正的T[]。
您不应该担心它不是最终的,因为它是在类中管理的。
注意,在push()上需要一个非空对象才能获得要使用的类型,因此我添加了一个对您所推送的数据的检查,并在那里抛出异常。
不过,这有点没有意义:通过push存储数据,方法的签名保证只有T个元素可以进入。所以数组是Object[]还是T[]或多或少是无关紧要的。
我找到了一种快速简便的方法。注意,我只在Java JDK 8上使用了它。我不知道它是否能与以前的版本兼容。
虽然不能实例化特定类型参数的泛型数组,但可以将已经创建的数组传递给泛型类构造函数。
class GenArray <T> {
private T theArray[]; // reference array
// ...
GenArray(T[] arr) {
theArray = arr;
}
// Do whatever with the array...
}
现在在main中,我们可以像这样创建数组:
class GenArrayDemo {
public static void main(String[] args) {
int size = 10; // array size
// Here we can instantiate the array of the type we want, say Character (no primitive types allowed in generics)
Character[] ar = new Character[size];
GenArray<Character> = new Character<>(ar); // create the generic Array
// ...
}
}
为了更灵活地使用数组,您可以使用链表。数组列表和在Java.util.ArrayList类中找到的其他方法。