Java object equality

I have a four domain objects in my project. They have 3 common attributes namely id, name and age.

public class Domain1 {
       private String id;
       private String name;
       private int age;
       ...
}

public class Domain2 {
       private String id;
       private String name;
       private int age;
       ...
}

public class Domain3 {
       private String id;
       private String name;
       private int age;
       ...
}

public class Domain4 {
       private String id;
       private String name;
       private int age;
       ...
}

Domain1 and Domain4 comparison is only based on 'id' attribute when compared with other domains (Domain2, Domain3 and Domain4) or with each other. Domain2 and Domain3 comparison is based on id, name and age except when compared to each other.

For ex,

Domain1 equal Domain2 - equality based on id
Domain1 equal Domain3 - equality based on id
Domain1 equal Domain4 - equality based on id
Domain2 equal Domain3 - equality based on id, name and attribute
Domain2 equal Domain4 - equality based on id
Domain3 equal Domain4 - equality based on id

so on...

How can implement such a equality requirement?

Jon Skeet
people
quotationmark

I would just try not to do this. The rules you've suggested violate the requirements of Object.equals, in particular:

It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

Now consider your rules with:

Domain1 d1 = new Domain1("id1", "name1", "attribute1");
Domain2 d2 = new Domain2("id1", "name1", "attribute1");
Domain3 d3 = new Domain3("id1", "name3", "attribute3");

Now d2.equals(d1) is true (they match on ID) and d1.equals(d3) is true (they match on ID) but d2.equals(d3) is false, because they don't match on attribute and name.

I don't think I remember ever seeing equality across entirely disparate types working out nicely. It's hard enough trying to avoid surprises in a superclass/subclass relationship, but this is worse.

people

See more on this question at Stackoverflow