• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Detecting Duplicates in Hashmap

 
Ravi Bansal
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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???
 
Henry Wong
author
Marshal
Pie
Posts: 21021
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
as equals and hashcode methods are correctly overriden.


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

Henry
 
Ravi Bansal
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks alot Henry....it was typo
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic