在一個循環中,我試圖創建一個新的對象並將其添加到現有的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,但顯然這並沒有改變。
客戶端類構造函數的外觀如何? – Satyajit
顯示剩餘的代碼 - 至少在循環結尾 – Bohemian
顯示客戶類 - 循環看起來很好。 (沒有看到客戶端類,勞倫斯的答案看起來像是一個很好的猜測) –