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);
}
}
If you mean that when you store such objects as a key in a Map or in a Set they get lost, you might want to have a look at this thread which explains why storing mutable objects in a set in not a good idea, especially if they change while being held by the set.
Extract from the Set javadoc:
Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With