I am thinking of using a Set of BusinessObjects in Java. My intention is, that in each set there should be only ONE instance of each business object, but one business object can be shared across many sets. So, as an example:
BO1 - instance of BusinessObject1
BO11 - instance of BusinessObject1
BO2 - instance of BusinessObject2
this is correct
[BO1, BO2] or [BO1]
but this isn’t
[BO1, BO11]
Since I wanted to make sure this is enforced, I was thinking of specifying an AbstractBusinessObject like this:
public abstract class AbstractBusinessObject {
@Override
public int hashCode() {
return this.getClass().getName().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj != null)
return this.getClass() == obj.getClass();
return false;
}
}
Do you think that is a good idea?
Why not simply use Enums?
You can use
Enumof business objects andEnumSetof Business Objects.Tutorial here
Now if your business object are not designed for above purpose then just implement equals and hashcode in a normal way.
HashSet add method will anyway ignore duplicates.
This link discusses about equals and hashcode contract.
For Business objects general rule is equals and hashcode needs to be implemented using your business object PK.
Like For Employee object employee number can be considered as business key and pk can be different so equals and hashcode should based on employee number.