Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of vector in Java?

So, I want an array of Vector of Integer in Java.

If I put

Vector<Integer>[] matrix;
matrix = new Vector<Integer>[100];

I get cannot the compilation error

cannot create a generic array of Vector

Should I use

    matrix = new Vector[100];

instead? (which gives a warning)

Or should I simply not use an array of vectors and use vector of vector instead?

Note: I don't want a Vector< Integer >, I want a Vector< Integer >[] to create a matrix of Integers without using Integer[][].

like image 413
Mauricio Avatar asked Jun 01 '11 14:06

Mauricio


2 Answers

Java simply doesn't have any means to create arrays of a parameterized type without getting or suppressing a warning. So the best you can get is this:

@SuppressWarnings("unchecked")
Vector<Integer>[] anArray = (Vector<Integer>[]) new Vector<Integer>[100];

You can get around this problem if you avoid arrays entirely. I.e.:

Vector<Vector<Integer>> list = new Vector<Vector<Integer>>(100);

Or with the collection types:

List<List<Integer>> list = new ArrayList<List<Integer>>(100);
like image 191
x4u Avatar answered Oct 13 '22 19:10

x4u


Vector<Integer> vector = new Vector<Integer>();

If you try to do something like this:

Vector<Integer> vector = new Vector<Integer>();
Vector<Integer>[] vectors = {vector};

You will get a compile error:

Cannot create a generic array of Vector

However if you don't specify the generic type java will allow it but with a warning:

Vector<Integer> vector = new Vector<Integer>();
Vector[] vectors = {vector};
like image 44
Alfredo Osorio Avatar answered Oct 13 '22 19:10

Alfredo Osorio