0

I have a set of Car where class Car is as follows:

public class Car{ private Tyre tyre; private Engine engine; } 

In order to use Set for car for avoiding duplicates, I need to override hashcode and equals for Car class. My questions is do I also need to implement equals and hashcode for Tyre and Engine class?

1
  • If using eclipse you can right click in your source page, go to Source, then Generate hashCode() and equals(). Do this for all classes you need them in. You can then edit if you feel the need. Commented Feb 9, 2015 at 19:07

2 Answers 2

4

No, you don't.

If the equality of two Cars depends on the equality of the Tyres and Engines those cars have, then implementing equals and hashCode methods for the Tyre and Engine classes and delegating to them from Car's equals and hashCode methods is probably a very good idea. But if Car equality is determined some other way (like a car id, for example), then it might make perfect sense not to have equals or hashCode methods for Tyre and Engine.

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

Comments

2

If you will be using the hashCode results for your tyre and engine in the hashCode method for Car, then you will need to override hashCode in Tyre and Engine also. If you will be using the equals results for your tyre and engine in the equals method for Car, then you will need to override equals in Tyre and Engine also.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.