4

I've noticed that when I assign an object returned by map.get(key), the changes that I've done to the new object reflect in the original one(which is in the map). Is it returns a reference? Sorry I couldn't able to find a solid explanation for this. Also what about the other collections? Below is the sample code that I used.

Set<Id> idSet = new Set<Id>();
Map<Id, TestChild__c> children = new Map<Id, TestChild__c>([SELECT Id, Name FROM TestChild__c]);

public void methodOne(){
    idSet = children.keySet();
    for(Id childId : idset){
        TestChild__c child = new TestChild__c();
        child = children.get(childId);
        child.Name = 'TestOne';
        System.debug('Child Name : '+children.get(childId).Name); //result : TestOne
    }
}

2 Answers 2

5

You are correct - when you add a record to a collection, that simply passes a reference to the existing record. This means there would never be more than one instance of the record, regardless of how many collections you add it to.

This isn't explicitly documented in the Apex developer's guide, but it explained in the following developerforce blog post:

http://blogs.developerforce.com/developer-relations/2012/05/passing-parameters-by-reference-and-by-value-in-apex.html

This works in the same way as Java, and there are a number of posts explaining pass by reference versus value in Java - here's one example:

https://stackoverflow.com/questions/40480/is-java-pass-by-reference/7034719#7034719

3
  • Really hepled! But a confusion. Isn't it violate encapsulation? without using clone I feel like it always violate it. But using clone for each will mess the memory.Am I wandering?
    – highfive
    Commented Apr 1, 2014 at 8:19
  • I don't see how that breaks encapsulation - none of the data-hiding or bundling of methods and data are affected by multiple references to a record. If you need a separate copy, then using clone is the correct mechanism. Commented Apr 1, 2014 at 8:21
  • Got it @Bob Buzzard. I focused on your SOF link and for a moment I was thinking that if a field setter of a referenced object can be called without going through our custom setter, and so. Anyway you cleared my confusion. I'll think on this as well.
    – highfive
    Commented Apr 1, 2014 at 8:31
4

Yes that is correct. Primitive types are passed by value and non-primitive by reference.

This is a really good explanation of how it works exactly.

If you want to make changes and not affect the record in your collection, I'd suggest to clone the record using the .clone() method and then add it to a separate collection if you need to perform a DML on.

1
  • 1
    Thanks @Bachovski. But I think the first statement need a change according to the blog. Anyway I got the idea.
    – highfive
    Commented Apr 1, 2014 at 8:21

You must log in to answer this question.

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