• 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

How does Set identify duplicates(by == or equals)

 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

I wanted to make sure that the meaningfully equal objects wont be added to a set. how can I do that? I tried the following but failed.
 
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
The HashSet class uses both the equals() and hashCode() method to determine equality. If the equals method reports that two objects are the same, but they have different hashcodes, then the contract is broken. It may or may not work.

Henry
 
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi
This returns the size as 1 as expected:

import java.util.*;

public class SetClass{
public static void main(String [] args)
{
Set<Dog> item = new HashSet<Dog>();
Dog a =new Dog("cody");
Dog b =new Dog("cody");
item.add(a);
item.add(b);

System.out.println(item.size());///prints 2(but I am expecting 1 as a.equals(b) is giving true
}


}


class Dog
{
String name;

public Dog(String n)
{
name =n;
}
public boolean equals(Object O)
{
return this.name.equals(((Dog)O).name);
}

public int hashCode(){
return name.hashCode();
}
}
 
reply
    Bookmark Topic Watch Topic
  • New Topic