gpt4 book ai didi

java - 多次添加后获取 Vector 中的重复元素

转载 作者:行者123 更新时间:2023-11-29 06:11:32 25 4
gpt4 key购买 nike

在一个循环中,我试图创建一个新的对象并将其添加到现有的 Vector 中,但在每次迭代中,先前的元素都会发生变化,并且所有元素最终都变得相同。最后一个是复制的。这就像我正在创建相同的对象,或提供相同的引用。但我在每次迭代时都会创建一个新对象(好吧,我猜)。

 static Vector myclients = new Vector();//note : this is an attribute of 
//the all class, not just of that method, and I call those methods
// from the main of the same class

while ((strLine = br.readLine()) != null) {

if ( strLine.length() != 0 &&
! strLine.trim().substring(0,1).trim().equals("#")){
// splitting my string
String[] result = strLine.trim().split("\\s+");
int codigo = new Integer (Integer.parseInt(result[0].trim()) ) ;
String nome = new String (result[1].trim() );

try{
if (result[2].trim().equals("cliente")){
Cliente newcliente = new Cliente(codigo, nome);
Interface.err("Before addElement : "+myclientes.toString());
myclientes.addElement(newcliente);
Interface.err("after : "+myclientes.toString() );

}else if (){
// quite the same
}

}catch(Exception e){
Interface.err("pb ... : "+e);
}

} // if
} // while

我的客户端类有很多静态元素:

public class Client {
public static Integer code;
public static String name;
Client(){
code = null;
name = "undefined";
}

Client(Integer code, String name){
this.code = code;
this.name = name;
}

我得到的是:

Before addElement : []
after : [Vincent 0]
Before addElement : [emilie 999]
after : [emilie 999, emilie 999]
Before addElement : [vince 5, vince 5]
after : [bob 5, bob 5, bob 5]

这里有类似的问题 elements of arraylist duplicated但这对我没有帮助......

感谢您的帮助!

ps:我刚刚尝试为代码和名称构建一个新的整数和字符串,但显然这没有任何改变。

最佳答案

由于您每次都在创建一个新的 Client 对象,因此 Client 中的字段看起来可能是静态的,而实际上它们不应该是静态的。

关于java - 多次添加后获取 Vector 中的重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6658345/

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