*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How does Set identify duplicates(by == or equals) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How does Set identify duplicates(by == or equals)" Watch "How does Set identify duplicates(by == or equals)" New topic
Author

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

Mary John
Ranch Hand

Joined: Sep 17, 2007
Posts: 109
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.


SCJP 5.0<br />SCJD working on it
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18756
    
  40

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


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

Joined: May 04, 2006
Posts: 56
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();
}
}
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: How does Set identify duplicates(by == or equals)