This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Map interface with hashCode() method

 
Ajay Singh Rathore
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rahul Shilpakar
Ranch Hand
Posts: 132
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic