赞
踩
Its very simple but somehow not working (weird!!).
I have a List of a class type. I am adding objects to the list in a for loop. Up till adding object everything is Ok, but as soon as I try to access the list, only the last object's values are shown (refer to the output I have shown below). Also here is the code:
List myClassList = new ArrayList();
myClass myClassObj = new myClass();
for(int i=0;i
myClassObj.setProperty1("value1");
myClassObj.setProperty2("value2");
myClassObj.setProperty3("value3");
...
...Others
...
System.out.println(myClassList.add(myClassObj));
}
System.out.println(myClassList.size());/
for(int i=0;i
System.out.println(myClassList.get(i).getProperty1());/
.....
.....Others
.....
}
Iterator mcItr = myClassList.iterator();
while(mcItr.hasNext()){
myClass obj = mcItr.next();
System.out.println(obj.getProperty1());
.....
.....Others
.....
}
The output of this program is (if the size of someArray is 5) :
//'true' --> 5 times. Printed by the 'add' statement as it returns 'true' when everything is OK
//5 --> Size of 'myClassList' this is also OK
//Here the values corresponding to the fifth and the last object are printed and repeated 5 times. Instead of printing each objects value once. (whichever way of printing to console I may use, the result is same).
Here I can not figure out whether I am creating the list in a wrong way or accessing it in a wrong way.
Please advice.
Thanks!!
解决方案
When populating the list, you are repeatedly adding references to the same object. To fix, move the myClassObj initialization into the loop:
for(int i=0;i
myClass myClassObj = new myClass(); //
myClassObj.setProperty1("value1");
This will create a separate object for every element of the list.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。