This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes HashSet class allows duplicate objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashSet class allows duplicate objects?" Watch "HashSet class allows duplicate objects?" New topic

HashSet class allows duplicate objects?

Sachin Ravi

Joined: Jul 07, 2003
Posts: 1
Hi friends,
I want to create a HashSet consisting of objects of a "HostChannel" class which is defined as follows. My doubt is, why does it ALLOW duplicate objects (having same values of member variables) although I've overridden the "equals" method to compare contents and not references of objects. Note: The HashSet class implements the "Set" interface which by definition doesn't allow two duplicate objects e1,e2 such that e1.equals(e2).
When I add "HostChannel" objects to the HashSet I expect it to call "equals" automatically for checking for uniqueness of objects. Kindly help me figure why is the HashSet not using my "equals" method, and still comparing only references of objects being added(i.e. you cannot add the same object twice, but you can add two objects with the same member variable values).
public class HostChannel
private String m_strHost;
private String m_strChannel;
public HostChannel()
m_strHost = "";
m_strChannel = "";
public String getHost()
return m_strHost;
public void setHost(String f_strHost)
m_strHost = f_strHost;

public String getChannel()
return m_strChannel;
public void setChannel(String f_strChannel)
m_strChannel = f_strChannel;

public boolean equals (Object f_objObject)
HostChannel l_objHostChannel = (HostChannel) f_objObject;
if ( m_strHost.equals( l_objHostChannel.getHost() ) && m_strChannel.equals( l_objHostChannel.getChannel() ) )
return true;
return false;

} //end of class
Michael Morris
Ranch Hand

Joined: Jan 30, 2002
Posts: 3451
Hi Sachin,
Welcome to JavaRanch. You need to override the hashCode() method as well as the equals() method. If two objects are equal according to the equals() method then they must return the same hashCode(). If you don't override hashCode() then the all objects of the class will return a different code based on identity.

Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
I agree. Here's the link:
subject: HashSet class allows duplicate objects?
It's not a secret anymore!