簡體   English   中英

將幾個向量添加到向量向量不起作用,Java

[英]Add several Vectors to a Vector of Vectors doesn't work, 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]

Vector row只保留對t的引用,它不復制其元素。 當你改變t外,你正在影響row的內容。

而不是使用t.clear()使用t = new Vector()來創建新對象而不影響已添加到rows

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM