Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it proper for equals() to depend only on an ID?

Let's suppose I have class User:

public class User {   private Long id;   private String name;   private Integer age;   private BigDecimal account;   // other fields, getters and setters } 

Is it proper to override the equals method as follows?

@Override public boolean equals(Object ob) {    if (ob == null) {        return false;    }    if (this == ob) {        return true;    }    if (ob instanceof User) {        User other = (User) ob;        return this.id.equals(other.getId());    }    return false; } 

It turns out that the uniqueness of an object is determined only by its ID. But in my application, id is always unique. It's provided at the database. Is my equals implementation competent enough to account for this? Or is this not best practice?

Of course I understand that in this case the hashCode implementation should be the following:

@Override public int hashCode() {    return id.intValue(); } 
like image 223
Michael Avatar asked Jun 08 '13 20:06

Michael


People also ask

What is equals () used for?

The equals() method compares two strings, and returns true if the strings are equal, and false if not.

Can you use equals () with objects?

The equals() method is a static method of the Objects class that accepts two objects and checks if the objects are equal. If both the objects point to null , then equals() returns true .

What is the correct signature of the equals () method?

Here is the method signature of equals() method. equals() method takes one argument “obj” of type Object class and returns true if object calling this method is same as “obj”. For example, if a1 and a2 are two reference variables of type class A and they are pointing to same object then invoking a1.

Should I use equals or ==?

== should be used during reference comparison. == checks if both references points to same location or not. equals() method should be used for content comparison. equals() method evaluates the content to check the equality.


1 Answers

Whether you should do this depends on the semantics of your class. That is, what does it mean to say that two objects of your class are equivalent?

The most important distinction is between objects with value semantics and objects with entity semantics. Entity objects are not equivalent even if they have equivalent attributes (colour, length, etc.). In many cases, including when the object has been read from a database table that has a primary key, entity objects will have an ID field that is unique. Comparing only the ID field in that case is the right thing to do.

like image 182
Raedwald Avatar answered Sep 22 '22 19:09

Raedwald