0

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.

1
  • In the code snippet you define 2 classes, but in text you mention 2 objects. I still don't see a valid question. Commented Aug 22, 2012 at 16:30

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I guess the problem is actually getting to this situation. Thanks for the answer
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.