-1

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}

  • 2
    `List(GelirList) finalList = new ArrayList<>;` - That is not valid Java code. --- "*... the elements of the previous list are crushed.*" - What is that supposed to mean? – Turing85 May 01 '19 at 10:53

2 Answers2

0

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

Lino
  • 19,604
  • 6
  • 47
  • 65
0

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

while(iterator.hasNext()){
   GelirList firstList = new GelirList();
   //then the initialization
}
Bishal Jaiswal
  • 1,684
  • 13
  • 15