Java:将对象添加到对象列表中 [英] Java : Adding objects to a list of objects
问题描述
它非常简单但不知何故不起作用(奇怪!!)。
Its very simple but somehow not working (weird!!).
我有一个类类型的列表。我在for循环中将对象添加到列表中。直到添加对象一切正常,但是一旦我尝试访问列表,只显示最后一个对象的值(参考我在下面显示的输出)。这里是代码:
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<myClass> myClassList = new ArrayList<myClass>();
myClass myClassObj = new myClass();
for(int i=0;i<someArray.length;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<myClassList.size();i++){
System.out.println(myClassList.get(i).getProperty1());/////////////////
.....
.....Others
.....
}
Iterator<myClass> mcItr = myClassList.iterator();
while(mcItr.hasNext()){
myClass obj = mcItr.next();
System.out.println(obj.getProperty1());
.....
.....Others
.....
}
此程序的输出(如果 someArray
的大小为 5 ):
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.
请建议。
谢谢!!
推荐答案
填充列表时,您反复将引用添加到同一对象。要解决此问题,请将 myClassObj
初始化移至循环中:
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<someArray.length;i++){
myClass myClassObj = new myClass(); // <---- moved this into the loop
myClassObj.setProperty1("value1");
这将为列表的每个元素创建一个单独的对象。
This will create a separate object for every element of the list.
这篇关于Java:将对象添加到对象列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!