Bilbo Baggins
Bilbo Baggins

Reputation: 3019

Objects with null id are same?

In one of the applications I was working I found that they were considering two objects with the null id are different, is this a correct behavior of equals() method in java?

sample implementation is as follow ::

public boolean equals(Object obj) {
if (this == obj) {
            return true;
        }
        if (obj != null && obj instanceof A) {
            A a = (A) obj;
            // If the id is null then its considered as different object.
            if (a.getId() != null && a.getId().equals(this.getId())) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
}

Upvotes: 1

Views: 387

Answers (3)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79857

The most likely application of this kind of thing is that these are objects that get inserted into a database, and selected from the database. Generally, an ID would get assigned by the database at the time of insert.

This means that if you have objects with IDs, they're in the database. If two objects have the same ID, then they both represent the same row in the database.

But if objects don't have IDs, then you've created them, but you haven't inserted them in the database yet. If you have two such objects, both without IDs, then these will eventually end up as two different rows in the database. But for now, they just exist within your application. Nonetheless, if they are two different objects, then they really do represent two different items of data - and therefore equals should return false for these two objects.

Upvotes: 1

Krease
Krease

Reputation: 16215

It's perfectly fine, though it's probably wrong. It would mean that for b = a.clone(), a.equals(b) == true would vary depending on whether the id was null or not...

Rules of equals are pretty much a.equals(b) == b.equals(a).

Watch out though, as your method in question isn't actually overriding equals(Object), but is defining a different method (I assume that's just a question typo though).

Upvotes: 0

Makoto
Makoto

Reputation: 106470

The way I read this: the null ID from the incoming object makes these two objects not equal. That seems like a straightforward rationale; I can't say that nothing is equal to something.

(Oh, and an aside: the equals implementation is actually busted. It needs to be passing in the other object obj before it'd work.)

Upvotes: 0

Related Questions