Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an array of string vectors in Java?

I use the following code try to create an array of string vectors, I hope to have an array of 3 items, each item is a string vector :

Vector<String> Result_Vector_Array[]=new Vector<String>[3];

But NB highlighted the line as error(generic array creation), what's wrong ? What's the correct way to do it ? I know there is also Arraylist, but it's not synchronized, so I want to use vector.

like image 768
Frank Avatar asked Dec 18 '22 07:12

Frank


2 Answers

Due to type erasure, the JVM doesn't know at runtime that you have a Vector of String. The best it can do is create a 'raw' Vector. It can't guarantee for you that all Vectors actually contain Strings. That's why you get a warning from your IDE.

One way to work around this, it cast it, as jgubby suggests. Another is to put a List into your Vectors, instead of an array.

But, more importantly, why can the array have only 3 items? Wouldn't it be better to create a class with three fields to put into your Vector? With three items, that's not too much work, and you get the added bonus that you can give each of the three elements a helpful name, which should make your code a lot clearer.

Also, since Java 6, there exist a number of useful new synchronized List implementations, which might perform better than Vector, such as CopyOnWriteArrayList, or wrap a regular List in a Collections.synchronizedList.

like image 199
jqno Avatar answered Jan 07 '23 08:01

jqno


You cannot create an array like that, do this:

Vector<String> Result_Vector_Array[] = (Vector<String>[]) new Vector[3];

I would suggest a different approach - arrays of containers like that are often quite hard to use, and don't help in the understanding of your code.

PS Also worth noting that the java naming convention would be

 Vector<String> resultVectorArray[] = (Vector<String>[]) new Vector[3];

and it's not usual to include the type in the name (I suspect this will be contentious!), why not just call it 'result' and let the type system worry about the type?

like image 24
gub Avatar answered Jan 07 '23 08:01

gub