I have a simple class Role:
@Entity
@Table (name = "ROLE")
public class Role implements Serializable {
@Id
@GeneratedValue
private Integer id;
@Column
private String roleName;
public Role () { }
public Role (String roleName) {
this.roleName = roleName;
}
public void setId (Integer id) {
this.id = id;
}
public Integer getId () {
return id;
}
public void setRoleName (String roleName) {
this.roleName = roleName;
}
public String getRoleName () {
return roleName;
}
}
Now I want to override its methods equals and hashCode. My first suggestion is:
public boolean equals (Object obj) {
if (obj instanceof Role) {
return ((Role)obj).getRoleName ().equals (roleName);
}
return false;
}
public int hashCode () {
return id;
}
But when I create new Role object, its id is null. That's why I have some problem with hashCode method implementation. Now I can simply return roleName.hashCode ()
but what if roleName is not necessary field? I'm almost sure that it's not so difficult to make up more complicated example which can't be solved by returning hashCode of one of its fields.
So I'd like to see some links to related discussions or to hear your experience of solving this problem. Thanks!