aspose file tools*
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 Java 8 in Action this week in the Java 8 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: 36575
    
  16
I think your interpretation is correct
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18136
    
  39

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)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Objects as Map keys without Hashcode and equals.
 
Similar Threads
Issue in Working with Maps
equal() & hashcode()
Sorting a HasMap by Values
collections- MAP USE
Question from John Meyer's Mock