aspose file tools*
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "HashSet class allows duplicate objects?" Watch "HashSet class allows duplicate objects?" New topic
Author

HashSet class allows duplicate objects?

Sachin Ravi
Greenhorn

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: http://aspose.com/file-tools
 
subject: HashSet class allows duplicate objects?