• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

HashSet class allows duplicate objects?

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic