当前位置:   article > 正文

Java对象添加:简单却不正常

java list插入object

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.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/212676?site
推荐阅读
相关标签