-4

I have a program where the equals() method has been overridden,but the hashcode() is not but according to the java contract between these two, the hashcode must also be overridden. in that case i just want to override the hashcode() without causing any changes in the flow of the program. im not using the hashcodes generated to insert into any hashmap or hashtable. so just tell me the best solution to override the hashcode().

  • 1
    Both are not good options. look at the following question and answer, it gives guidlines for overriding hashCode and equals: http://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java – Icewind Mar 06 '15 at 12:24
  • 3
    the first one is an infinite recursion. The other one is also bad. – Eran Mar 06 '15 at 12:24
  • 2
    Just implement `hashCode()` correctly; it will be much better than any other option you may think of. – fge Mar 06 '15 at 12:26

1 Answers1

0

As @fge points out, the best solution is to implement hashcode() properly, even if you don't expect to use it.

But if you decide to ignore this and not implement hashcode() properly, then I recommend you implement it like this:

public int  int hashcode() {
    // Fail fast!
    throw new UnsupportedOperationException("hashcode");
}

Your two proposed "solutions" are problematic if you (or someone else maintaining your code) forgets, and puts instances of this class into a hash table.

The problem with this one:

public int  int hashcode() {
    return 0;
}

is that it will give you pessimal performance.

Your other proposal:

public int  int hashcode() {
    return this.hashcode();
}

is either going to fail (with a StackOverflowError exception) or go into an infinite loop if it is used. The actual behaviour is (at least in theory) platform specific.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216