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 Objects as Map keys without Hashcode and equals. 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 "Objects as Map keys without Hashcode and equals." Watch "Objects as Map keys without Hashcode and equals." New topic
Author

Objects as Map keys without Hashcode and equals.

Ved Antani
Greenhorn

Joined: Jan 05, 2003
Posts: 28

Output is:
first
second


How does this "get" method behave ? As both m1 and M2 have same values and I have not overridden hashcode(), will Object class's equals() method be called ?
I think the behaviour is like this:
1. There is no hashcode method so there is no way for the JVM to see if objects m1 and m2 contain different values
2. There is no equals method overridden so Object class's equals() is invoked and as both objects are different the code above works fine without m2 replacing m1's value.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38461
    
  23
I think your interpretation is correct
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

Ved Antani wrote:
Output is:
first
second


How does this "get" method behave ? As both m1 and M2 have same values and I have not overridden hashcode(), will Object class's equals() method be called ?
I think the behaviour is like this:
1. There is no hashcode method so there is no way for the JVM to see if objects m1 and m2 contain different values
2. There is no equals method overridden so Object class's equals() is invoked and as both objects are different the code above works fine without m2 replacing m1's value.


1. There is no hashCode() method defined so it will be inherited from the Object class. This method will try to create a unique value per instance -- this value is also called the identity hash code.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
Consider Paul's rocket mass heater.
 
subject: Objects as Map keys without Hashcode and equals.