The Secret Life of an SObject: Equality, Sets and Maps



When testing for equality between sObjects in Apex, it is the sObjects’ properties – the values of the sObjects’ fields – which are compared. So two separate sObject instances that have the same field values are considered equal:

But, if we were to mimic our sObject using a custom Apex type, we would find that by default, two instances with the same property values would not be considered equal:

See Method Declarations in Anonymous Apex

This is because with Apex classes we have to decide how we want equality to be evaluated, by defining our own equals method.

If we don’t define an equals method then the equality operator will compare object references (memory locations) – in other words asking “are these references to the exact same instance?”

If we wish, we can make the same reference comparison with sObjects too, using the exact equality and exact inequality operators.


View original post 599 more words