I`m having some trouble figuring out how to implement a working hashcode for the below example:
I have 2 classes :
Class A
{
}
Class B
{
protected List<A> constitutingObjects;
}
Already overridded equal so object A equals object B if A is part of B.constitutingObects.
The issue I have is that i`m not sure how to implement the Hashcode for this.
Any ideas ?
Thanks.
TL;DR: What you’re trying to do doesn’t make sense. Take a step back and try to tackle your bigger task in a different way.
That sounds like a very bad idea. It’s hard to tell what these objects are meant to represent, but something containing a collection isn’t logically equal to an element of that collection – a shopping list isn’t equal to “milk”.
Don’t forget that you must follow the requirements specified by the
java.lang.Objectdocumentation. Lots of other code will depend on those guarantees.Implementing
hashCodewill basically be impossible unless you just return a constant. The hash code of two equal objects has to be equal, which means the hash code of any instance ofClassBwould have to be equal to the hash code of every element ofconstitutingObjects, which means that all of those elements would have to have the same hash code. Unless instances ofClassAsomehow “knew” what their container was, I don’t see how this could be possible.