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]
当你再次将它添加到'rows'时,'t'仍然是相同的参考。 – irrelephant
感谢您的回答。但我能做什么呢? – Kinnocchio
注意事项:如果线程安全性是需求,则使用ArrayList而不是Vector('Collections.synchronizedList(new ArrayList())'),并使用Iterator而不是Enumeration。 – ignis