0

我有三个列表,在第三个列表中我正在合并两个列表。如果我在第三个中进行更改,为什么更改会反映到其他列表以及如何克服?

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);
        }
      }

由于上述更改也反映到其他列表中。如何克服

4

1 回答 1

1

因此,在 java 中,对象是通过引用传递的。在这种情况下,当你addAllmergedCommunication它上面添加了来自两个列表的所有对象的引用,即communicationToListcommunicationFromListto mergedCommunication。因此,其中的Communication对象mergedCommunication与其他两个列表中的对象相同。

**建议:**如果您不想修改原始对象,可以进行克隆。

于 2019-11-20T09:33:31.770 回答