开发者

get duplicated elements in Vector after multiple add

开发者 https://www.devze.com 2023-03-20 02:03 出处:网络
In a loop I am trying to create a new Object and add it to an existing Vector, but at each iteration the previous elements changes and all of them become finally the same. The last one is replicated.

In a loop I am trying to create a new Object and add it to an existing Vector, but at each iteration the previous elements changes and all of them become finally the same. The last one is replicated. It's like if I was creating the same Object, or giving the same reference. But I create a new Object at each iteration (well, I guess).

 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 ( s开发者_StackOverflow社区trLine.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

My Client class has got a lot of static elements :

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;
  }

}

And what I get is :

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]

There's kind of the same question here elements of arraylist duplicated but it didn't help me ...

Thanks for your help !

ps : I just tried building a new Integer and String for code and name, but apparently that changes nothing.


Since you're creating a new Client object each time it looks like the fields in Client may be static when they shouldn't be.

0

精彩评论

暂无评论...
验证码 换一张
取 消