在java中创建一个通用数组

我试图在java中创建一个通用数组 – 我遇到了一些问题 – 如何创建一个大小为6并且内部有一个byte []和一个Integer的元组数组?

谢谢

private Tuple[] alternativeImages1 = new Tuple[6]; class Tuple { public final F first; public final S second; public Tuple(final F first, final S second) { this.first = first; this.second = second; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Tuple tuple = (Tuple) o; return this.first == tuple.first && this.second == tuple.second; } @Override public int hashCode() { int result = this.first != null ? first.hashCode() : 0; result = 31 * result + (this.second != null ? second.hashCode() : 0); return result; } } 

那么你可以使用原始类型:

 Tuple[] array = new Tuple[6]; 

或者您可以进行未经检查的转换:

 Tuple[] array = (Tuple[])new Tuple[6]; // or just this because raw types let you do it Tuple[] array = new Tuple[6]; 

或者您可以使用List代替:

 List> list = new ArrayList>(); 

我推荐使用List。

在前两个选项之间进行选择,我建议使用未经检查的转换,因为它将为您提供编译时检查。 但是,如果你在其中放入一些其他类型的元组,它将不会抛出ArrayStoreException。