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
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
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.
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.