简体   繁体   English

如何使用arraylist复制另一个arraylist

[英]How to arraylist to copy another arraylist

Using the iterator, I want to add array to another array list.使用迭代器,我想将数组添加到另一个数组列表中。 but after the elements of the first list are added to the second list, the elements of the previous list are crushed.但是在第一个列表的元素添加到第二个列表之后,前一个列表的元素被粉碎。 How do I prevent this?我如何防止这种情况?

GelirList firsList = new GelirList();
List(GelirList) finalList =  new ArrayList<>;

Iterator<DvzGelir> iterator = input.getGelirlist().iterator();

while(iterator.hasNext()){
DvzGelir exList = (DvzGelir) iterator.next()

firstList.setName(exList.getName());
firstList.setNumber(exList.getNumber());

finalList.add(firstList);
}

I expect the output of : {eren,123}, {ezel,234}, but the actual output is {eren,123}, {eren,123}我期望输出:{eren,123}, {ezel,234},但实际输出是 {eren,123}, {eren,123}

You have to initialize firstList in every loop iteration instead of declaring it once outside of the loop:您必须在每次循环迭代中初始化firstList而不是在循环外声明一次:

while(iterator.hasNext()){
    GelirList firstList = new GelirList();
    ....
}

You have to do that, else you are always editing the same reference .你必须这样做,否则你总是在编辑相同的参考

For more information about how Java works in this aspect, I suggest reading this other post: Is Java “pass-by-reference” or “pass-by-value”?有关 Java 在这方面如何工作的更多信息,我建议阅读另一篇文章: Java 是“按引用传递”还是“按值传递”?

Since GelirList is a reference type, so the same data gets updated.由于GelirList是引用类型,因此更新相同的数据。 Use this:用这个:

while(iterator.hasNext()){
   GelirList firstList = new GelirList();
   //then the initialization
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM