Re: Set and .equals() semantics
On Thu, 8 May 2008, Mike Schilling wrote:
"Rex Mottram" <rexm@not.here> wrote in message
news:_-idna618o9tG77VnZ2dnUVZ_uOdnZ2d@comcast.com...
Mike Schilling wrote:
"Mark Space" <markspace@sbc.global.net> wrote in message
news:U4JUj.2702$3O7.1685@newssvr19.news.prodigy.net...
Rex Mottram wrote:
which can both look up and retrieve a reference. But I hope I'm
misunderstanding something which would allow me to use the more natural
Set design.
Nope, I think I agree. Set and subclasses could benefit from a "find()"
method which does an equals() or hashcode() lookup as appropriate and
returns the element already in the set.
That is, every set should build a hash table of its contents whether it
needs one or not? I disagree. (Though it would be trivial to add find()
specifically to HashSet, which is implemented on top of HashMap.)
Why is the "trivality" limited to HashSet? Every Set must implement a
contains() method, so they will all have a way of navigating through their
collection, zeroing in on a target object, and using equals() to determine
if it's a match. A find() method would in all cases be identical to
contains() except for returning the object reference rather than a
boolean. No?
You can build a set using whatever mechanism you like. A TreeSet navigates
using the compareTo() method and thus only works on Comparables. I could
build a Set that assumes that some other interface or method entirely will
produce a useful comparison or classification.
Set.contains() works because it's assumed that we're looking for that very
object, so that any method called on the object will return the proper
value. Set.find(key) would have to assume that any method called on the key
provided would return the proper value, even though the key and the actual
object may be different objects (and would by default have different hash
codes).
Yes. That's a starting assumption here.
If Set contained find(), each different Set implementation would have to
document what the key and the actual object needed to have in common.
Yes, *exactly as they do at present*.
Come to think of it, I lied You can't easily add find() to HashSet either,
because there's no guarantee that the key and actualy object have the same
has code value. I was right in the first place: use a Map.
If there's no guarantee that the key and actual object have the same hash
code value, and don't compareTo in the same way, then a Map also won't
work!
The whole point here is that you can have two distinct objects which have
the same behaviour with respect to the operations that your set is using,
and you'd like to be able to use one to fish out the other. Rex is
absolutely right in saying that the existence of contains implies the
possibility of find.
tom
--
.... the gripping first chapter, which literally grips you because it's
printed on a large clamp.