java object 添加,Java:将对象添加到对象列表中

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值