I am coding a system where I have objects which represent a set of resources. These resources are identifiable (they have an ID). There can only be one resource with the same ID, and so multiple objects with the same ID really should have the same values.
My problem is with the equality concept in this case. Should it be based on the ID or on the values alone? Is object A = object B because they have the same ID OR should object A == object B because their fields are the same.
One possibility I was thinking of was to have the ID-based comparison be "equals" and the field-based comparison be "equivalent". Alternatively I could have it so the field-based comparison was "equals" and the ID based comparison was "representSameObject" (or something). Just a pseudo-code example:
class A {
String uuid;
int field1;
double field2;
List<String> listField;
@Override
public boolean equals(Object other) {
return uuid.equals(other.uuid);
}
public boolean equivalent( other ) {
if (this == other) {
return true;
}
if (null == other) {
return false;
}
if (other.getClass() != this.getClass()) {
return false;
}
A rhs = (A) other;
return new EqualsBuilder().append(field1, rhs.field1).append(field2, rhs.field2).append(listField, other.listField).isEquals();
}
}
In the end this may come down to a personal preference coupled with system requirements, but I am very interested to learn how others have approached this concept. It has been annoying the heck our of me since I started on this project!
If it makes a difference I am programming at the minute in Java. I don't mind where the answer comes from though as this is obviously a conceptual issue.
==
andequals
, although I do bemoan the lack of operator over-riding in Java. I'm just looking for how to approach the concept. I'll update the answer to represent java code though. thanks.