0

I have Three List and in the third list i'm merging two list. if i make changes in third why the change gets reflect to other list and how to overcome?

List<Communication> communicationFromList = fromTicket.getCommunications();
List<Communication> communicationToList = toTicket.getCommunications();
List<Communication>  mergedCommunication=new  ArrayList<>();

mergedCommunication.addAll(communicationToList);
mergedCommunication.addAll(communicationFromList);

for (int i = index; i < mergedCommunication.size(); i++) {
        if (!ObjectUtils.isEmpty(mergedCommunication.get(i))) {
          int j =i;
         Communication communication = mergedCommunication.get(i);
         communication.setCommSeqId(++j);
         communication.setMergeInfo("Merged From: " + fromTicketId);
        }
      }

Due Above changes gets reflect over to other list also.how to overcome

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86

1 Answers1

1

So, in java objects are passed over by reference. In this case when you did addAll on mergedCommunication it added reference of all objects from both lists i.e. communicationToList and communicationFromListto mergedCommunication. Hence, the Communication objects in mergedCommunication are the same objects as in other two lists.

**Suggestion:**If you don't want to modify original objects you can do cloning.

Vinay Prajapati
  • 7,199
  • 9
  • 45
  • 86
  • Java objects are NOT passed over by reference! This is a misconception and wrong. Java is Pass By Value: https://www.journaldev.com/3884/java-is-pass-by-value-and-not-pass-by-reference – D. Lawrence Nov 25 '19 at 14:29
  • that's a wrong blog. the variables o1 and o2 are referencing the objects but are not the same reference variables as in the method calling this method. In short, what you see on internet is not a truth, it's just information always test it out else you will always find yourself in trouble. Java passes primitives by value but objects by reference. – Vinay Prajapati Nov 25 '19 at 15:14
  • Maybe I should reference stackOverflow then if that makes more sense to you: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value/40523#40523 An object has for value a reference. This reference is pass by value, even if it is a reference. – D. Lawrence Nov 25 '19 at 15:19
  • 1
    `Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it.` Hope that line is clearly understood. And if I rephrase this objects memory locatios are eventually passed (which are being called values here). So, this is what I am saying. But thanks for your answer. – Vinay Prajapati Nov 25 '19 at 15:21