Reputation: 10297
I have a class that contains a large number of data members - some of which are user defined classes of their own, Lists, HashMaps, etc...
Let's say there are 20 data members.
Is there a more pragmatic way to override the equals()
operator other than checking for equality against every single field?
For example (using Guava):
HashMap<k,v> dataMember1;
String dataMember2;
CustomClass dataMember3;
etc...
@Override
public boolean equals(Object obj) {
Objects.deepEquals(this.dataMember1, obj.dataMember1) &&
Objects.equals(this.dataMember2, obj.dataMember2) &&
Objects.equals(this.dataMember3, obj.dataMember3) &&
etc...
}
I've seen these large blocks in production code before, but they always seemed so redundant.
Upvotes: 1
Views: 96
Reputation: 2599
There is an annotation processor for Java called Lombok, which offers some nice annotations to deal with boilerplate code, including @EqualsAndHashCode.
In cases when immutability is acceptable/desirable, Immutables and Google AutoValue libraries provide annotations for creating value classes along with all the boilerplate code, including equals()
method.
Upvotes: 2
Reputation: 33992
I think how you're implementing the equals
is fine, however it may be a code smell that you should pull some of those fields into their own classes. Then you would be comparing fewer fields, as each class can implement its own equals
.
Regardless, the problem is a symptom, not a cause.
Upvotes: 1