How to implement hashCode cleanly?

Being able to write your own equals/hashCode for a custom class seems appealing – see Non-primitive Types in Map Keys and Sets. But with no hashCode method exposed in Apex string or decimal or any of the other primitive types, building a correct and efficient hashCode for a custom class that has a few fields of different types looks way harder than it should be.



Summer’13 Update:

According to the Summer’13 release notes String now provides a hashCode method! Here is the sample code included in the release notes here.

public class MyCustomClass {
    String x,y;
    public MyCustomClass(String a, String b) {
    public Integer hashCode() {
        return (31 * x.hashCode()) ^ y.hashCode();
    public Boolean equals(Object obj) {
        if (obj instanceof MyCustomClass) {
            MyCustomClass p = (MyCustomClass)obj;
            return (x.equals(p.x)) && (y.equals(p.y));
        return false;

Original Answer:

Converted comment to an answer after a bit of digging around.

Initial thoughts…

Yes most interesting, I did wonder why the only sample was using numbers. It also looks like there is a bug in this area at large anyway,

Current conclusion…

I had a look at the Java implementations and a few other general postings on the net. My conclusion is that given the statement governor, at least for strings, it is going to quite expensive to implement a String.hashCode. We really need a native implementation of this to avoid hitting the statement governor very quickly with large maps.

Some interesting links

Source : Link , Question Author : Keith C , Answer Author : Community

Leave a Comment