May 10, 2010

Remembering References

This should be common knowledge for any Apex developer but it can be easy to forget at times and may be confusing to those new to the platform (especially if you're not from a Java background). When you create a variable using a primitive type, for example the Integer type, that variable represents the Integer; when you create an instance of a class using new your variable stores a reference to the object.

This can come in very handy when dealing with maps and other collections:

public class MyClass 
{ 
   public Integer m_iVal {get; set;} 
   public MyClass(Integer iVal) 
   { 
      m_iVal = iVal; 
   } 
} 
Map myMap = new Map(); 
// put some objects in the map 
myMap.put(0, new MyClass(3)); 
myMap.put(1, new MyClass(6)); 

Now we can use get to retrieve the reference to the object, and then we can use that reference to modify the object:

MyClass valueOne = myMap.get(1); 
valueOne.m_iVal = 9;

Now if you looked at the value stored in myMap.get(1).m_iVal you would find that it's 9. Of course, Strings are immutable (you can not change them) and so act like other primitive types, i.e. if this was a map of Strings or Integers then when you use .get() you actually get a copy of the object in the map, not a reference, so changing it will not affect the object stored in the map.

You can even put your object reference into another collection and then modify it from there - which can be very handy in triggers when you need to create a custom way of looking up objects being passed to the trigger by some other field.