Where’s my hashCode?


Every now and then we run into code where the what is written does not reflect the author’s intent, that’s a bad thing.  Here’s an example of Java code that does not reflect the author’s intent most of the time.

pubic class Foo {
    private int[] myInts;
    // Constructors...
    // Methods...
    public int hashCode() {
        return this.myInts.hashCode();
    }
}

What’s the problem? The catch here is that invoking hashCode() on an array does not take into consideration the data that resides inside the array and is the same as invoking System.identityCode(…).  This could lead to potential problems when using hash code dependent structures such as HashSet or HashMap.  If you run the following code you will find that both printouts are identical.

public class Test {
    public static void main ( String[] args ) {
        int[] a = new int[1];
        a[0] = 1;
        System.out.println(a.hashCode()); // A value
        a[0] = 5000;
        System.out.println(a.hashCode()); // That value again
    }
}

What do we do then?  The fix for this is to use the Arrays.hashCode(…) method which is overloaded for all of the primitive arrays and Object array as well.  The usage of Arrays.hashCode(…) is shown below.

public class Test {
    public static void main ( String[] args ) {
        int[] a = new int[1];
        a[0] = 1;
        System.out.println(Arrays.hashCode(a)); // A value
        a[0] = 5000;
        System.out.println(Arrays.hashCode(a)); // Another value
    }
}

Be careful when using methods, be absolutely certain about the behavior of the methods you invoke.  If you are a developer and recognize that you are doing something that might look questionable then document defensively for fear that another developer may come along and fix your “mistake” which was actually what you intended.

Share this post:
  • RSS
  • Digg
  • Reddit
  • Twitter
  1. No comments yet.
(will not be published)