Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Mary John
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • 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.
 
Henry Wong
author
Marshal
Pie
Posts: 21216
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
Ganesha Kumar
Ranch Hand
Posts: 56
  • Mark post as helpful
  • send pies
  • 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();
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic