如何创建字符串向量Java中的数组? [英] How to create an array of string vectors in Java?
问题描述
我用下面的code尝试创建的字符串向量的数组,我希望有3个项目的数组,每个项目是一个字符串矢量:
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];
但NB强调了行错误(通用阵列创建),有什么不对?什么是做了正确的方法是什么?我知道有也ArrayList中,但它不是同步的,所以我想用向量。
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.
推荐答案
由于类型消除时,JVM不知道在运行时,你有字符串
的矢量
。它可以做的最好的是创建一个原始的矢量。它不能保证你所有的矢量
5事实上包含字符串
秒。这就是为什么你从你的IDE得到一个警告。
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 Vector
s actually contain String
s. That's why you get a warning from your IDE.
一个办法来解决这个问题,把它转换它,因为jgubby建议。另一种方法是把列表
到矢量
S,而不是数组。
One way to work around this, it cast it, as jgubby suggests. Another is to put a List
into your Vector
s, instead of an array.
但是,更重要的是,为什么可以在阵列只有3个项目?那岂不是更好地创建一个类有三个字段,把你的矢量
?随着三个项目,这不是太多的工作,你会得到额外的奖励,你可以给每个的三个要素一个有用的名称,它应该让你的code更清晰了很多。
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.
此外,由于Java 6中,存在着许多有用的新同步列表
实现,这可能会表现得比矢量$ C $更好C>,如<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/concurrent/CopyOnWriteArrayList.html\"><$c$c>CopyOnWriteArrayList$c$c>,或者换一个普通的
列表
在<一个href=\"http://java.sun.com/javase/6/docs/api/java/util/Collections.html#synchronizedList%28java.util.List%29\"><$c$c>Collections.synchronizedList$c$c>.
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
.
这篇关于如何创建字符串向量Java中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!