所以,我想在Java中使用Vector of Integer数组。
如果我把
Vector<Integer>[] matrix;
matrix = new Vector<Integer>[100];
我得到的不能是编译错误
无法创建Vector
的通用数组
我应该使用
matrix = new Vector[100];
代替? (发出警告)
或者我应该简单地不使用向量数组而是使用向量向量?
注意:我不想要Vector&lt;整数&gt;,我想要一个Vector&lt;整数&gt; []在不使用Integer [] []的情况下创建整数矩阵。
答案 0 :(得分:7)
Java没有任何方法可以在不获取或禁止警告的情况下创建参数化类型的数组。所以你能得到的最好的是:
@SuppressWarnings("unchecked")
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector<Integer>[100];
如果完全避免使用数组,则可以解决此问题。即:
Vector<Vector<Integer>> list = new Vector<Vector<Integer>>(100);
或者使用集合类型:
List<List<Integer>> list = new ArrayList<List<Integer>>(100);
答案 1 :(得分:3)
Vector<Integer> vector = new Vector<Integer>();
如果您尝试执行以下操作:
Vector<Integer> vector = new Vector<Integer>();
Vector<Integer>[] vectors = {vector};
您将收到编译错误:
无法创建通用数组 向量
但是如果你没有指定泛型类型,java会允许它,但会带有警告:
Vector<Integer> vector = new Vector<Integer>();
Vector[] vectors = {vector};
答案 2 :(得分:1)
向量由数组支持,并且会增大或缩小到足以容纳插入元素的大小。因此,您可以预先分配Vector,但不必在创建时实际指定大小。
// preallocated vector, which can hold 100 elements
Vector<Integer> integers = new Vector(100);
// default vector, which will probably grow a couple of times when adding 100 element
Vector<Integer> integers = new Vector();
真正的Java数组无法增长或缩小,并且不支持从中点删除元素。要分配数组,请使用
// allocate an array
Integer[] integers = new Integer[100];
现在,如果你想拥有一个“矢量数组”,你就可以
// array of vectors
Vector[] vectors = new Vector[100];
答案 3 :(得分:0)
要创建通用数组,您必须创建非泛型并投射它。您还必须初始化数组中的所有元素,否则它们将为null。 :(
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new Vector<Integer>();
但是,由于Vector是一个遗留类,在Java 1.2(1998)中被ArrayList取代,我将使用List作为接口,使用ArrayList进行实现。
List<Integer>[] anArray = (List<Integer>[]) new List[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new ArrayList<Integer>();
另一个选择是使用包含原始int
而不是Integer
对象的集合。如果需要,这可以提高性能。
TIntArrayList[] anArray = new TIntArrayList[100];
for(int i = 0; i < anArray.length; i++)
anArray[i] = new TIntArrayList();
答案 4 :(得分:0)
为避免类型转换,请考虑以下实现:
Vector<Integer>[] intVectorArray;
Vector[] temp = new Vector[desiredSize];
intVectorArray = temp;
for(int i = 0;i<intVectorArray.length;i++){
hashArray[i] = new Vector<Integer>();
}
新创建的intVectorArray
将继承通用的Vector-Array类型temp
以提供所需的维度,for
循环将实例化您想要的数据类型。
当您准备在Integer
的元素上调用intVectorArray
函数时,您将全部完成!