ArrayList.Contains behaviour

  • Thread starter Thread starter Ton van den Heuvel
  • Start date Start date
T

Ton van den Heuvel

Hi,

I just noticed that ArrayList.Contains(Object obj) uses the Equals
method of the object that is passed to the Contains method to check
for equality with the object in the list. Wouldn't it be more logical
to use the Equals method of the objects in the list?

Regards,
Ton van den Heuvel
 
Ton van den Heuvel said:
I just noticed that ArrayList.Contains(Object obj) uses the Equals
method of the object that is passed to the Contains method to check
for equality with the object in the list. Wouldn't it be more logical
to use the Equals method of the objects in the list?

Why? They should be identical, and if you think about it from the JIT's
point of view, it only needs to do one lookup to find the method
implementation, and then call that single method multiple times with
different parameters, which I would imagine is more efficient
(certainly in terms of the code cache locality of reference) than
looking up lots of different methods and calling each of those with the
same parameter.
 
Jon Skeet said:
Why? They should be identical, and if you think about it from the JIT's
point of view, it only needs to do one lookup to find the method
implementation, and then call that single method multiple times with
different parameters, which I would imagine is more efficient
(certainly in terms of the code cache locality of reference) than
looking up lots of different methods and calling each of those with the
same parameter.

Good point. In terms of efficiency the current method is the best one.
Since it isn't properly described in the documentation which Equals
method is used, it caused some trouble finding out I actually had to
override the Equals method of the object passed to the Contains
method.

Regards,
Ton van den Heuvel
 
Ton van den Heuvel said:
Good point. In terms of efficiency the current method is the best one.
Since it isn't properly described in the documentation which Equals
method is used, it caused some trouble finding out I actually had to
override the Equals method of the object passed to the Contains
method.

But if you'd been following the contract of Equals, it shouldn't have
made any difference. From the documentation:

<quote>
The following statements must be true for all implementations of the
Equals method. In the list, x, y, and z represent object references
that are not a null reference (Nothing in Visual Basic).

<snip>

x.Equals(y) returns the same value as y.Equals(x).
</quote>

Given that contract, Hashtable shouldn't have to specify which version
is used - the result should be the same.
 
Back
Top