System.hashCode still broken for Id

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…

Answer

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.

Attribution
Source : Link , Question Author : Keith C , Answer Author : sfdcfox

Leave a Comment