When using sets in combination with objects of a custom Apex type is see some strange behaviour.
First of all I'm implementing the equals() and hashcode() function in my class so that the Set uses those functions to decide what objects are the same.
This is for example how my object class looks like:
public with sharing class MyObject
{
@AuraEnabled
public String UniqueName {get;set;}
public MyObject(String name)
{
this.UniqueName = name;
}
public Boolean equals(Object obj)
{
System.debug('Checking equals');
MyObject def = (MyObject)obj;
return def.UniqueName == this.UniqueName;
}
public Integer hasCode()
{
System.debug('called hashcode');
return this.UniqueName.hashCode();
}
}
Now if I run the following code I get some strange behaviour:
Set<MyObject> myObjects= new Set<MyObject>();
myObjects.add(new MyObject('Test'));
myObjects.add(new MyObject('Test'));
At this point I see that my Set contains 2 objects. Yet in fact per definition of my equals method they are the same. Checking the debug logs I notice that my own equals method is never called.
By accident I found that the following works correctly:
Set<MyObject> myObjects= new Set<MyObject>();
System.debug(myObjects);
myObjects.add(new MyObject('Test'));
myObjects.add(new MyObject('Test'));
This time I see that when I add an object it calls the equals method. So it seems that System.debug is triggering something?
Not sure what to think at the moment honestly... Anyone who has seen this issue before or who knows what I'm doing wrong?