tags:

views:

55

answers:

2

Hi,

If I add custom class objects to HashSet and don't provide hashCode() methods on them, how does it impact the perfomance of hashing?

Thanks, Ajay

+1  A: 

if you don't define your own hashCode method, the method from the parent Class of your object gets called. If you have no parent defined the hashCode method from the Object class gets called. According to the java api documentation the method returns an integer depending on the address of the object - but how exactly this is accomplished depends on the jvm and the operating system.

In summary - if you don't specify any hashCode methods it's like putting Objects in the hashTable.

Nikolaus Gradwohl
Specifically, the `Object` documentation says that "As much as is reasonably practical, the hashCode method defined by class `Object` does return distinct integers for distinct objects." For collections which rely on `hashCode()`, this is a good thing.
Brian S
I happened to look at the code and found that it does something like the following:-hashCode = 31 * hashCode + elementHashCode;In http://www.docjar.com/html/api/java/util/Arrays.java.htmlDo you think this will give a unique hashCode for eah different object? I am not convinced about it?Also, for a very large set of objects in an array or long string etc. would it not overlow the limit of Integer? It is multiplying by 31 eerytime.
ajay
+2  A: 

The stock implementation as Nikolaus mentions is fast and will work just fine. You should not hesitate to use it except when you are overriding the equals method. For example, if two Person objects are "equal" if they have the same getFirstName() and getLastName() you would override the equals method to check that, and also override the hashCode() to return the same hash when the values for those two properties are the same.

Kirk Woll
Perhaps easier to say "if x.equals(y) is true then x.hashCode() == y.hashCode() MUST be true" (in order to use the object as a key in any hash based structure).
Mike Q