System.hashCode broken on Id properties of SObjects?

The workaround is shown in the question: convert the Id to a String first to get a consistent hashCode:

Account a = ...;
Integer hashCode = System.hashCode(String.valueOf(a.Id))

PS I've created a case with Salesforce reporting the bug.


Update: Fixed!

I just tested this in a Spring '21 sandbox and it is fixed! The Known Issue still says In Review but I assume that's because the release isn't in production instances yet.

Note that this is a versioned behavior change beginning with version 51.0. It's called out in the release notes here.


This is still broken. I worked with support to get the scenario added to the known issue referenced in the original question (https://success.salesforce.com/issues_view?id=a1p300000008YQ0AAM).

Note that I reproduced the issue a bit differently, using the following code:

Id id1 = UserInfo.getUserId();
Id id2 = UserInfo.getUserId();
// passes, the ids are equal
System.assert(id1.equals(id2));
// fails, the hashcodes are not equal
System.assertEquals(System.hashCode(id1), System.hashCode(id2));

Tags:

Hashcode

Apex