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 Java in General and the fly likes Detecting Duplicates in Hashmap 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 » Java in General
Bookmark "Detecting Duplicates in Hashmap" Watch "Detecting Duplicates in Hashmap" New topic
Author

Detecting Duplicates in Hashmap

Ravi Bansal
Ranch Hand

Joined: Aug 18, 2008
Posts: 84
In the following code , size of the hashmap should come out as 2 as equals and hashcode methods are correctly overriden. it should view as t1 and t2 objects as duplicates.

import java.util.*;
public class MapEQ {
public static void main(String s[]){
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, "Ravi");
m.put(t2, "Kumar");
m.put(t3, "Bansal");
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 of this is coming as 3. Can anyone tell me why the t1 and t2 are not viewed as duplicates???


SCJP 5.0 94%
OCE-EJBD 90%
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18754
    
  40

as equals and hashcode methods are correctly overriden.


Unfortunately, it is the hashCode() method that needs to be overridden -- Java is case sensitive.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ravi Bansal
Ranch Hand

Joined: Aug 18, 2008
Posts: 84
Thanks alot Henry....it was typo
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1761
    
    7

You should consider adding the @Override annotation to all methods that you intend to be override implementations. In this case the compiler would then have picked up on the fact that hashcode() doesn't override any inherited methods and an error to that effect would have been displayed.


Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Detecting Duplicates in Hashmap