2

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?

  • Doesn't sound like what you are seeing but FYI about the interaction with debug log levels hashCode() is never called when adding to Maps and Sets. – Keith C Nov 8 '16 at 10:33
  • No indeed, I checked that one first but it doesn't really explain what I'm seeing. – Lieven Juwet Nov 8 '16 at 10:34
  • I just ran your code on eu6 and it functioned correctly. – Keith C Nov 8 '16 at 10:42
  • Strange, my DEV org is also located on EU6. I'll try to run the same code on a different org. – Lieven Juwet Nov 8 '16 at 10:52
  • 1
    Using your advice I started from scratch and found the issue. Stupid typo really, it said hasCode instead of hashCode so it was not implemented correctly. Still confusing why it works with System.debug one org and on the other it works without :/ anyways things are working. Thanks again. – Lieven Juwet Nov 8 '16 at 12:31
1

Found the issue, it was a typo (doh) in the hashCode method (it said hasCode).

Implementing the correct method fixed the issue. Still strange it works after a system.debug but whatever it works...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.