3

I need a best way to avoid the object reference between two list. For example, I have list of Contact records and I create one more list in which I make the changes to each record's LastName. My problem is, if I make changes in new list, the first list last name also changes. Here is my code.

list<contact> cont = new List<contact>([select id, lastName from contact where lastname Like '%xyz%' Limit 3]);
list<Contact> editedCont = new List<Contact>();
editedCont.addAll(cont);
for(contact c: editedCont)
   c.lastname = 'abc';
System.debug(cont);
System.debug(editedcont);
0

2 Answers 2

4

You don't need to loop at all, this is exactly what List.deepClone() is for.

From the List documentation

deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber)

Makes a duplicate copy of a list of sObject records, including the sObject records themselves.

This is in contrast to the regular clone() method, whose documentation says

clone()

Makes a duplicate copy of a list.

Note that if this is a list of sObject records, the duplicate list will only be a shallow copy of the list. That is, the duplicate will have references to each object, but the sObject records themselves will not be duplicated.

To also copy the sObject records, you must use the deepClone method.

Since you do want to make copies of the sObject records themselves, deepClone() is what you'd want to use.

5
  • 1
    I mean...you do still need to loop through if you want to set all the LastName fields to a specific value.
    – Adrian Larson
    Commented Mar 25, 2017 at 20:32
  • 1
    @AdrianLarson Right, forgot about that bit. Though now that you say that, I wonder if it is possible to avoid all loops if you were to shove the cloned list into a StandardSetController (SSC), set a field on the prototype object of the SSC, and then use StandardSetController.save(). Of course, assuming that would work, you'd only be able to set the target field(s) of all the records to a common value.
    – Derek F
    Commented Mar 25, 2017 at 21:22
  • 1
    Wouldn't be too much work to test out! :)
    – Adrian Larson
    Commented Mar 25, 2017 at 22:53
  • deepClone works for sObject list only, any suggestions for a custom List<T> of any type?
    – VarunC
    Commented Dec 12, 2018 at 12:54
  • @VarunC Not at the moment. This sounds worthy of being its own question.
    – Derek F
    Commented Dec 12, 2018 at 15:50
2

Something like this will get you going.. not sure exactly what you're trying to do

List<Contact> contactsToUpdate = new List<Contact>();

for(Contact c: [select id, lastName from contact where lastname Like '%xyz%' Limit 3])
{
    c.lastname = 'abc';
    contactsToUpdate.add(c);

}

update contactsToUpdate;
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .