如何在 Vector Java 的 Vector 中查找(打印)指定字段

How to find (print) specified field in a Vector of Vector Java

我们必须打印此向量的指定索引,但无法获取正确的索引。

创建SetA后,所有元素对应最后一次插入,而不是指定索引

有没有办法在现有矢量的末尾添加一个 Vector? 这样,函数"add"就不行了!

    Vector <Vector <Integer>> setA = new Vector<Vector <Integer>>();
    Vector <Integer> temp = new Vector<Integer>();

    for(int i=0; i<=2;i++){
        temp.clear();

        for(int j=0; j<=4;j++){
            temp.add(i*j);
        }                   
        setA.add(temp);
        System.out.printf("\nVector Temp: "+temp.toString());
        System.out.printf("\nElement i="+i+" of setA: "+setA.get(i).toString()+"\n");
    }
    System.out.printf("\nNow I want to print the vector that correspond index i=1 of set");
    System.out.printf("\n"+setA.get(1).toString()+"\n\n");
}

问题是,您正在尝试一次又一次地重复使用相同的 Temp,例如:

for(int i=0; i<=2;i++){
    temp.clear();

    for(int j=0; j<=4;j++){
        temp.add(i*j);
    }                   
 setA.add(temp);

因此,当您开始时,您清除了 temp,添加了四个元素并添加了对向量 setA 的相同引用。现在当你下次循环时,即 i=1,你从 temp 中删除所有元素,所以现在你的 setA 将在位置 i =0;

包含一个空向量

因此,为避免这种情况,您应该使用:

 for(int i=0; i<=2;i++){
    temp = new Vector<Integer>();//initialize every time. Do you really need Vector or list will work?

    for(int j=0; j<=4;j++){
        temp.add(i*j);
    }                   
    setA.add(temp);//do you  really need vector within vector?

您每次都在循环中添加对 temp 的相同引用。您想每次都声明一个新实例。

for (int i = 0; i <= 2; i++) {
    Vector <Integer> temp = new Vector<Integer>();
    ...
}

此外,您应该真正使用 List/ArrayList,因为 Vector 是遗留的。