Apex and Object References

I learned something today that I’m not sure how I made it this far without knowing. It was confusing the heck out of me, so I thought I’d share. When you assign one object to another through the use of the “=” operator, it doesn’t actually make a copy of the object. Instead, it makes a reference to the object. What does this mean? Let me try to explain with some code:

Account a = new Account(Name = 'Test');
Account b = a; //here we set a reference to a
b.Name = 'Changed'; //changing b also changes a
System.assertEquals('Changed', a.Name);

If you want to make a copy of the object, then you need to use the clone method to make a copy of the object:

Account a = new Account(Name = 'Test');
Account b = a.clone();
b.Name = 'Changed';
System.assertEquals('Test', a.Name);
Advertisements

3 thoughts on “Apex and Object References

  1. Pingback: Force.com From Around the Web: May 5, 2012

  2. Pingback: All Things Being Equal « ForceAdventure

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s