2011-07-12 16 views
1

在一個循環中,我試圖創建一個新的對象並將其添加到現有的Vector中,但是在每次迭代中以前的元素都會發生變化,並且它們全都變成相同。最後一個被複制。這就像是我創建相同的對象,或者給出相同的參考。但是,我在每次迭代中創建一個新對象(我想)。在多次添加後在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:我只是試着爲代碼和名稱構建一個新的Integer和String,但顯然這並沒有改變。

+1

客戶端類構造函數的外觀如何? – Satyajit

+0

顯示剩餘的代碼 - 至少在循環結尾 – Bohemian

+0

顯示客戶類 - 循環看起來很好。 (沒有看到客戶端類,勞倫斯的答案看起來像是一個很好的猜測) –

回答

3

由於您每次創建新的客戶端對象時,它看起來像客戶端中的字段可能是靜態的,而不應該是靜態的。

+0

+1我認爲最好的猜測,由於缺少代碼 – Bohemian

+0

而且他們是! wooops,我已經注意到了,但它創造了比我想象的更多的問題...(張貼更多的代碼) – vincent

+0

所以我想我的項目設計的很糟糕,因爲我在主類中使用myclients Vector( - >需要靜態)調用上述代碼(在同一類的其他方法中)( - >,最後得到靜態pbs)。 – vincent