user2938723
user2938723

Reputation: 1130

Overriding equals and hashcode?

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?

Upvotes: 0

Views: 83

Answers (2)

Sean Reilly
Sean Reilly

Reputation: 21836

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.

Upvotes: 4

rgettman
rgettman

Reputation: 178253

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.

Upvotes: 2

Related Questions