2009-07-10 72 views
4

我使用下面的代码尝试创建串矢量的阵列,我希望有3项阵列,每个项是字符串向量:如何在Java中创建一个字符串向量数组?

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

但是NB强调线作为误差(通用阵列创造),出了什么问题?什么是正确的方法来做到这一点?我知道也有Arraylist,但它不同步,所以我想使用矢量。

+0

什么是一个字符串矢量? – Mnementh 2009-07-10 20:21:19

+0

是不是不推荐使用? – Tom 2009-07-10 20:23:21

+0

P.S.使用ArrayList来代替! – jjnguy 2009-07-10 20:23:40

回答

6

由于type erasure时,JVM不知道在运行时,你有StringVector。它能做的最好的是创建一个“原始”向量。它不能保证所有Vector s实际上包含String s。这就是为什么你从IDE获得警告。

解决这个问题的一种方法就是按照jgubby的说法进行投射。另一种方法是将List放入您的Vector中,而不是数组。

但是,更重要的是,为什么阵列只有3个项目?创建一个带有三个字段的课程,将其放入您的Vector不是更好吗?有三个项目,这不是太多的工作,你可以得到额外的奖励,你可以给三个元素的每一个一个有用的名字,这应该使你的代码更清晰。

另外,由于Java 6中,存在许多的有用的新的同步List实现方式中,这可能会执行超过Vector更好,如CopyOnWriteArrayList,或者在Collections.synchronizedList包裹经常List

5

你不能创造这样一个数组,这样做:

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

我会建议不同的方法 - 像集装箱的阵列往往是相当难用,并在理解不帮你的代码。

PS另外值得一提的是,Java的命名约定将

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

,它不是通常包括在名称(我怀疑这将是有争议的!)的类型,为什么不把它称作“结果'让类型系统担心类型?使用反射

0

这将是:

Vector<String>[] arrayOfVectors = 
     (Vector<String>[]) java.lang.reflect.Array.newInstance(Vector.class, size); 
    java.util.Arrays.fill(arrayOfVectors, new Vector<String>()); 
    for (Vector<String> v : arrayOfVectors) { 
     System.out.println(v); 
    } 

或者你可以使用一个ArrayList,然后用包起来Collections#synchronizedList(java.util.List)

1

您还可以创建:

Vector<Vector<String>> Result_Vector_Array=new Vector<Vector<String>>(); 

或者可以替换Vector与其他一些收藏。

1

我建议保持与收藏,这样做

Collection<Vector<String>> resultVectorArray = new ArrayList<Vector<String>>(3); 

然后你可以使用与构造泛型,实际上讲的同样的效果

0

如果你想使用同步的ArrayList,你可以使用java.util.Collections中的synchronizedList方法。

ArrayList<String> a1 = new ArrayList<String>(); 
ArrayList<String> a2= new ArrayList<String>(); 
ArrayList<String> a3 = new ArrayList<String>(); 

ArrayList<String> array[] = (ArrayList<String>[]) new ArrayList[3]; 

array[0]= Collections.synchronizedList(a1); 
array[1]= Collections.synchronizedList(a2); 
array[2]= Collections.synchronizedList(a3); 
-1

我应该了解你要使用多线程该阵列上?...

如果你没有,那么你不必担心同步。

我想:

List<List<String>> listOfLists = new ArrayList<List<String>>(); 

    List<String> firstVector = new ArrayList<String>(); 

    firstVector.add("one"); 
    firstVector.add("two"); 

    listOfLists.add( firstVector); 

    System.out.println(listOfLists.get(0).get(0) == "one"); 
    System.out.println(listOfLists.get(0).get(1) == "two"); 

打印真实的,真正的

相关问题