I have a class that contains a collection. The two instances of the class are equal if the contents of the collection are equal. While I am building my data structure I store the class in a HashSet, and the contents of the collection change. The changes cause a change in the hash code value. This seems to cause side effects where my data is lost in the Set. Removing the collection from the hashcode calculation fixes the problem, but violates rule where all fields in equals should be used in the hashcode.
How would you implement the hashcode in this situation?
public class LeveZeroHolder
{
private final Set<LevelOneHolder> orgGroups = new HashSet<LevelOneHolder>();
private final String name;
public LeveZeroHolder(String name, LevelOneHolder og)
{
this.name = name;
orgGroups.add(og);
og.setFA(this);
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null || obj.getClass () != getClass ())
return false;
LeveZeroHolder hobj = (LeveZeroHolder)obj;
return getOrgGroups().equals(hobj.getOrgGroups()) && getName().equals(hobj.getName());
}
@Override
public int hashCode()
{
int rs = 17;
rs = rs * 37 + ((getName() == null) ? 0 : getName().hashCode ());
rs = rs * 37 + ((getOrgGroups() == null) ? 0 : getOrgGroups().hashCode());
return rs;
}
public String getName()
{
return name;
}
public Set<LevelOneHolder> getOrgGroups()
{
return orgGroups;
}
public void addOrgGroup(LevelOneHolder o)
{
o.setFA(this);
orgGroups.add(o);
}
}