This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes Collections- HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collections- HashMap" Watch "Collections- HashMap" New topic
Author

Collections- HashMap

Sarvarth Bhatnagar
Greenhorn

Joined: Jan 16, 2013
Posts: 9
What is the advantage of overriding hashcode in Gogx in code below. We can do the exact same thing with cat which does not override Hashcode


Result:
Gogx key
null
null
null
Cat key

Please explain the importance of overriding the Hashcode in Gogx.
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

Note: There is a bug in line 10 of your code. The method should have been named hashCode(), not hashcode(). Because it has the wrong name, it's not overriding hashCode() of class Object, and it will not be called.

You should use the @Override annotation to catch such mistakes:

And there is another bug, in line 15. You are comparing strings with == there. That does not work; use .equals() instead to compare strings.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Sarvarth Bhatnagar
Greenhorn

Joined: Jan 16, 2013
Posts: 9
my bad, Thanks Jesper! for the annotation suggestion
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38405
    
  23
Apart from the inconcistent indentation and spacing, which makes your code very difficult to read, you have some bad style in that equals method.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections- HashMap