Reputation: 310
I'm having some problems with the equals
method generated by Eclipse.
Suppose I have an Entity Bean with the attributes entityId
and name
, but I just selected for the equals generation the entityId
attribute. So, the code generated by eclipse is the following:
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entity other = (Entity) obj;
if (entityId == null) {
if (other.entityId != null)
return false;
} else if (!entityId.equals(other.entityId))
return false;
return true;
}
The problem is that when comparing two different instances of the class Entity
that have null
as the entityId, the equals
method returns true.
For me, this equals
implementation is not correct (at least when using it with JPA), because two entities without an entityId
are just object that are going (probably) to be persisted as new objects in a database. If I add these two objects to a Set (one to many relationship, for example), after the two insertions the Set is going to have just one element (Sets don't allow duplicates).
So, the question is why Eclipse generates the equals method like this? Do you think is better to implement the equals
method with the following code?
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Entity other = (Entity) obj;
if (entityId == null) {
if (other.entityId != null)
return false;
else
return true;
} else if (!entityId.equals(other.entityId))
return false;
return true;
}
Upvotes: 0
Views: 163
Reputation: 20455
Eclipse simply doesn't know about how you will use your class.
Usually if fields have equal values objects considered equal
class Human {
String name;
String petName;
}
Human("Bob", null)
is equal to Human("Bob", null)
.
You case is somewhat special, so you have to made adjustment by yourself.
Upvotes: 2