File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Map interface with hashCode() method" Watch "Map interface with hashCode() method" New topic

Map interface with hashCode() method

Ajay Singh Rathore

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");
} }
class ToDos{
String day;
ToDos(String d) { day = d; }
public boolean equals(Object o) {
return ((ToDos)o).day ==;
// public int hashCode() { return 9; }

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 -
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15100

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.
I agree. Here's the link:
subject: Map interface with hashCode() method
jQuery in Action, 3rd edition