Mihai
Mihai

Reputation: 3

hashcode implementation in java for

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.

Upvotes: 0

Views: 109

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1503180

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.

Already overridded equal so Class A equals Class B if A is part of B.constitutingObects

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.Object documentation. Lots of other code will depend on those guarantees.

Implementing hashCode will 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 of ClassB would have to be equal to the hash code of every element of constitutingObjects, which means that all of those elements would have to have the same hash code. Unless instances of ClassA somehow "knew" what their container was, I don't see how this could be possible.

Upvotes: 1

Dan D.
Dan D.

Reputation: 32391

When defining equals and hashCode in Java, you are not testing if 2 classes are equal, you are actually testing if 2 objects of the same type (class) can be equal, according to the equals method or they can be in the same "bucket" (logically group of objects) according to the hashCode.

So, if x and y are 2 objects of type A:

A x = new A();
A y = new A();
  • if x.equals(b) is true then x.hashCode() must be equal to y.hashCode()
  • if x.hashCode() == y.hashCode() then x.equals(y) could be true or false

Upvotes: 0

Related Questions