Newer Version Available
Using Custom Types in Map Keys and Sets
For maps, instances of your Apex classes can be added either as keys or values. If you add them as keys, there are some special rules that your class must implement for the map to function correctly; that is, for the key to fetch the right value. Similarly, if set elements are instances of your custom class, your class must follow those same rules.
When using a custom type (your Apex class) for the map key or set elements, provide equals and hashCode methods in your class. Apex uses these two methods to determine equality and uniqueness of keys for your objects.
Adding equals and hashCode Methods to Your Class
- The equals method with this
signature:Keep in mind the following when implementing the equals method. Assuming x, y, and z are non-null instances of your class, the equals method must be:
- Reflexive: x.equals(x)
- Symmetric: x.equals(y) should return true if and only if y.equals(x) returns true
- Transitive: if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true
- Consistent: multiple invocations of x.equals(y) consistently return true or consistently return false
- For any non-null reference value x, x.equals(null) should return false
The equals method in Apex is based on the equals method in Java.
- The hashCode method with this
signature:Keep in mind the following when implementing the hashCode method.
- If the hashCode method is invoked on the same object more than once during execution of an Apex request, it must return the same value.
- If two objects are equal, based on the equals method, hashCode must return the same value.
- If two objects are unequal, based on the result of the equals method, it is not required that hashCode return distinct values.
The hashCode method in Apex is based on the hashCode method in Java.
Sample
This sample shows how to implement the equals and hashCode methods. The class that provides those methods is listed first. It also contains a constructor that takes two Integers. The second example is a code snippet that creates three objects of the class, two of which have the same values. Next, map entries are added using the pair objects as keys. The sample verifies that the map has only two entries since the entry that was added last has the same key as the first entry, and hence, overwrote it. The sample then uses the == operator, which works as expected because the class implements equals. Also, some additional map operations are performed, like checking whether the map contains certain keys, and writing all keys and values to the debug log. Finally, the sample creates a set and adds the same objects to it. It verifies that the set size is two, since only two objects out of the three are unique.
This code snippet makes use of the PairNumbers class.