aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Map interface with hashCode() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Map interface with hashCode() method" Watch "Map interface with hashCode() method" New topic
Author

Map interface with hashCode() method

Ajay Singh Rathore
Greenhorn

Joined: Nov 20, 2007
Posts: 2
import java.util.*;
class MapEQ {
public static void main(String[] args) {
Map<ToDos, String> m = new HashMap<ToDos, String>();
ToDos t1 = new ToDos("Monday");
ToDos t2 = new ToDos("Monday");
ToDos t3 = new ToDos("Tuesday");
m.put(t1, "doLaundry");
m.put(t2, "payBills");
m.put(t3, "cleanAttic");
System.out.println(m.size());
} }
class ToDos{
String day;
ToDos(String d) { day = d; }
public boolean equals(Object o) {
return ((ToDos)o).day == this.day;
}
// public int hashCode() { return 9; }
}

output
3
if uncommented public int hashCode() method than output will be 2.

someone explain this what does happen when we uncommented hashCode() method.
Seema Gaurav
Ranch Hand

Joined: Apr 29, 2008
Posts: 47
Hey Ajay,
This has already been answered before, check this out - http://www.coderanch.com/t/268751/java-programmer-SCJP/certification/hashCode-equals
Thanks,
Seema
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14347
    
  22

Ajayr Singh, welcome to JavaRanch. Please note that we have a rule here: you are required to quote your sources when you post a question or code from a book, mock exam or other source.

Now, in this case from the other topic we know that code is from the K&B book.

Next time, make sure that you tell us where you copied the question from.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Rahul Shilpakar
Ranch Hand

Joined: Aug 29, 2006
Posts: 132
There is rule that if two objects are equal then their hashcode of both objects must be same.

Now, souppose if somebody overrides the equal method then he/she should also override its hashcode method, that means anybody implementing the equal method then he/she shall have to implement the hashcode mehtod.

But the viceversa is not true. i.e. if 2 objects have same hashcode it is not necessary that those 2 objects need to be equal.


Perform for today. Adapt for tomorrow.
 
wood burning stoves
 
subject: Map interface with hashCode() method