• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Detecting Duplicates in Hashmap

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks alot Henry....it was typo
 
Bartender
Posts: 1952
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Can you really tell me that we aren't dealing with suspicious baked goods? And then there is this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic