Reputation: 1130
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
Reputation: 21836
No, you don't.
If the equality of two Car
s depends on the equality of the Tyre
s and Engine
s 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
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