2012-12-12 74 views
1

我想将一些向量放入向量的向量。我在一个循环中完成这个操作,最后只有最后一个添加的矢量,但与我想添加的矢量的数量一样多。添加几个向量到向量的矢量不工作,Java

public void initVectors() { 

    rows = new Vector<Vector<String>>(); 
    Vector<String> data = new Vector<String>(); 

    Vector<String> t = new Vector<String>(); 
    String aLine; 
    try { 
     FileInputStream fin = new FileInputStream("module.txt"); 
     BufferedReader br = new BufferedReader(new InputStreamReader(fin)); 
     // extract data 
     while ((aLine = br.readLine()) != null) { 
      StringTokenizer st = new StringTokenizer(aLine, ","); 
      t.clear(); 
      while (st.hasMoreTokens()) { 
       t.addElement(st.nextToken()); 
       // System.out.println(st.nextToken()); 
      } 

      System.out.println(t); 
      System.out.println("add it"); 
      rows.addElement(t); 

     } 

     Enumeration vEnum = rows.elements(); 
     System.out.println("Elements in vector:"); 
     while (vEnum.hasMoreElements()) { 
      System.out.print(vEnum.nextElement()); 
      System.out.println(); 
     } 


     br.close(); 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

} 

我的输出是:
[GDI 1,4,1.0]
添加它
[Physik公司,6,1.3]
添加它
元素向量:
[Physik公司,6 ,1.3]
[Physik公司,6,1.3]

+0

当你再次将它添加到'rows'时,'t'仍然是相同的参考。 – irrelephant

+0

感谢您的回答。但我能做什么呢? – Kinnocchio

+1

注意事项:如果线程安全性是需求,则使用ArrayList而不是Vector('Collections.synchronizedList(new ArrayList())'),并使用Iterator而不是Enumeration。 – ignis

回答

3

Vectorrow保持只是一个参考到t,它不共它的元素。当您在外部更改t时,您正在影响row的内容。

而不是使用t.clear()使用t = new Vector()来创建一个新对象,而不会影响已添加到rows的内容。

+0

工作!谢谢。 – Kinnocchio