12

Five years ago there was System.hashCode broken on Id properties of SObjects? and I've just run into it again today. You can see the problem by running this test case:

@IsTest
static void hashCodeForId() {

    Account a = new Account(Name = 'Acme');
    insert a;

    System.assertEquals(
        System.hashCode((String) a.Id),
        System.hashCode((String) a.Id)
    );                                  // OK

    System.assertEquals(
        System.hashCode(a.Id),
        System.hashCode(a.Id)
    );                                  // Fails
}

It hurts when you build your own class that implements equals/hashCode that e.g. combines several properties where at least one is an Id. Also extra painful because when debugging is turned on hashCode isn't called at all in set/map logic so the problem is hidden.

The work-around is to turn the Ids into strings as shown in the above test. So the only question I have is whether laughing or crying is the appropriate response to this...

  • Definitely crying. That said, I'd be happy to open the third bug report in 30 days, I'm going for a record 😉. – sfdcfox Dec 2 '20 at 19:26
  • Yes please. Don't want to be posting this again in another 5 years... – Keith C Dec 2 '20 at 19:31
  • 2
    Oh, the KI has been updated this year, is in review. No need for another case, but I will ping someone to see if we can get even a tentative update. – sfdcfox Dec 2 '20 at 19:32
  • I'm with the tear-shedders on this one. – Phil W Dec 2 '20 at 19:48
  • 5
    There is something freaky about putting System.debug(System.hashCode(a.Id)); in a loop and watching it repeatedly output different hashes. – Daniel Ballinger Dec 2 '20 at 20:26
5

Per Chris Peterson:

Known. Fixed in next release. Doesn't impact apex collection correctness since they use magic to use a "proper" hashCode value thankfully.

Obviously, #SafeHarbor, but it should be fixed soon enough.

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.