Note that there are some explanatory texts on larger screens.

plurals
  1. POget duplicated elements in Vector after multiple add
    primarykey
    data
    text
    <p>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).</p> <pre><code> 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 &amp;&amp; ! 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 </code></pre> <p>My Client class has got a lot of static elements :</p> <pre><code>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; } </code></pre> <p>}</p> <p>And what I get is :</p> <pre><code>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] </code></pre> <p>There's kind of the same question here <a href="https://stackoverflow.com/questions/5626587/elements-of-arraylist-duplicated">elements of arraylist duplicated</a> but it didn't help me ...</p> <p>Thanks for your help !</p> <p>ps : I just tried building a new Integer and String for code and name, but apparently that changes nothing.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload