gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:28:34 25 4
gpt4 key购买 nike

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

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

有没有办法在现有 vector 的末尾添加一个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,添加四个元素并向 vector setA 添加相同的引用。现在,当您下次循环时,即 i=1,您将删除 temp 中的所有元素,因此现在您的 setA 将在位置 i =0 处包含一个空 vector ;

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

 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?

关于java - 如何在 Vector Java 的 Vector 中查找(打印)指定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29624592/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com