Ahmad
Ahmad

Reputation: 2190

Equals() method is called on existing object or incoming object in collections

Can anyone please clarify when we check equality on collections, equals() method is called on incoming object or on those objects which are there in collection. for ex. If a Set or a Hashmap has objects object1, object2 and object3 and a fourth object called object4 tries to get into the Set or it is compared with the already existing three objects in case of hashmap then equals() method is called on this fourth object and the already existing three objects are passed one by one or reverse is true.?

Upvotes: 2

Views: 213

Answers (4)

Ahmad
Ahmad

Reputation: 2190

Well...As I just checked in eclipse, the equals() method of incoming objects are called. Eclipse passes ref. of pre-existing objects in equals() method of incoming object one by one. I know as you all are saying, It is written in Sun's equals() method contract that equals method should be reflexive, symetric and transitive. This question came in mind when I was thinking that collections could have been more optimized if it is somehow checked pro-actively that the two references (that are being checked for equality) point to the same object or not. If they are, then it does make sense to by-pass equals() and hashcode() method.

Upvotes: 0

05storm26
05storm26

Reputation: 165

There's should be no diference between a.equals(b) and b.equals(a) (if a and b not null )The equals should be symmetric. There's no guarantee that what form(a.equals(b) or b.equals(a)) being used.

Upvotes: 2

njlarsson
njlarsson

Reputation: 2340

There is no way to know, unless you are considering a very specific collection implementation. You are not supposed to rely on it. The equals method should be reflexive, i.e., x.equals(y) should give the same result as y.equals(x), unless one of them is null.

Upvotes: 3

JB Nizet
JB Nizet

Reputation: 692081

The answer doesn't matter much (and might vary betwen implementations), because by contract, A.equals(B) if and only if B.equals(A). Not respecting this contract is a recipe for strange and incoherent behavior from the collections.

Upvotes: 6

Related Questions