This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
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 Elasticsearch in Action this week in the Big Data 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

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

Mary John
Ranch Hand

Joined: Sep 17, 2007
Posts: 109

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

Joined: Sep 28, 2004
Posts: 19344

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.


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

Joined: May 04, 2006
Posts: 56
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");

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)

public int hashCode(){
return name.hashCode();
I agree. Here's the link:
subject: How does Set identify duplicates(by == or equals)