简体   繁体   中英

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}

You have to initialize firstList in every loop iteration instead of declaring it once outside of the loop:

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”?

Since GelirList is a reference type, so the same data gets updated. Use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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