• Post Reply Bookmark Topic Watch Topic
  • New Topic

Some questions related to hashcode and equals  RSS feed

 
Sandeep Kumar B
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If we override equals, then we must override hashcode

1. Do I really need to do it if I choose to use a separate function defined in the class say compareID(int id) for equality?
When are we forced to invoke obj1.equals(obj2)

2. If my custom hashcode always returns same value for instance


public int hashCode() {

return 20;
}

Does that means that if I store these objects in a hashamp they all will have the same hash and hence in the same linked list? (Separate chaining )

3. If I choose never to store my objects in the collection, do I need to override hashcode or can I have the same hashcode for my objects? Is it good or bad for performance?
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, technically you don't have to do anything. However, if you want to write proper reusable code, you should adhere to the contracts.

Your class' hashCode() method may not be used right now, but it's difficult to predict in what way your class is going to be reused in the future. Especially if you release your class to the public domain. In short, classes you write should always do what they promise. And every class promises to provide a hash code that's compatible with the equals method.

And yes, providing a constant hash code for every different instance is going to hurt performance badly if you use hash tables/maps.
 
Sandeep Kumar B
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok Thanks
Is it a good or bad idea to have a static variable for hashcode and increment everytime when you need to generate it?
That will at least make sure thats its always unique
Thoughts?
 
Stephan van Hulst
Saloon Keeper
Posts: 7987
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How are you going to ensure that when you later create a new instance that is equal to one you created earlier, they are going to have the same hash code?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!