This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashSet class allows duplicate objects?

 
Sachin Ravi
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic