This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread 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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Detecting Duplicates in Hashmap" Watch "Detecting Duplicates in Hashmap" New topic

Detecting Duplicates in Hashmap

Ravi Bansal
Ranch Hand

Joined: Aug 18, 2008
Posts: 86
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");
class ToDos{
String day;
ToDos(String d){
public boolean equals(Object o){
return ((ToDos)o);

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%
Henry Wong

Joined: Sep 28, 2004
Posts: 20538

as equals and hashcode methods are correctly overriden.

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


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

Joined: Aug 18, 2008
Posts: 86
Thanks alot was typo
Jelle Klap

Joined: Mar 10, 2008
Posts: 1951

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:
subject: Detecting Duplicates in Hashmap
It's not a secret anymore!