今天學習struts中遇到了一個有趣的問題。
問題大致如下:
聲明一個value object的arrayList對象,然后從數據庫中讀取想添加到該list對象中,結果后來添加的對象覆蓋前賣添加的對象。起初代碼如下(后來寫的測試代碼):
1 public class Te { 2 @Test 3 public void test() { 4 Person person = new Person(); 5 ArrayList<Person> persons =new ArrayList<Te.Person>(); 6 int i=2; 7 while(i!=0){ 8 // if(!persons.isEmpty()) 9 // System.out.println(persons.get(persons.size()-1).getDescripton()); 10 i--; 11
person.setDescripton(i+"princess"); 12 person.setName(i+"knight"); 13 System.out.println(person.getDescripton()); 14 persons.add(person); 15 } 16 System.out.println(persons.get(0).getDescripton()); 17 System.out.println(persons.get(1).getDescripton()); 18 } 19 class Person{ 20 private String name; 21 public String getName() { 22 return name; 23 } 24 public void setName(String name) { 25 this.name = name; 26 } 27 public String getDescripton() { 28 return descripton; 29 } 30 public void setDescripton(String descripton) { 31 this.descripton = descripton; 32 } 33 private String descripton; 34 } 35 }
在while外面聲明一個Person對象person的目的是為了減少內存開銷,但是這樣做的結果就是list中存儲的對象都是用一個,最開始百思不得其解,於是加了激發昂注釋代碼,也就是文中注釋掉的那兩行,得到的結果如下圖:
仔細思考便找到了問題的所在,因為while循環外面聲明的person變量,在每一次循環后在list中都add了這個對象,也就是說list中每一個元素都指向了同一個對象,然而每一個次循環都在改變這個對象的私有屬性值,所以就造成了后面添加到list中對象覆蓋了前面添加的對象假象~~~,事實上他們壓根就是一個對象~~~