Re: Set and .equals() semantics
On Thu, 8 May 2008, Rex Mottram wrote:
Briefly, my app maintains a Collection of unique Foo() objects derived by
reading and parsing an InputStream. The objects being stored have an
equals() method which compares the important attributes. So far, very basic
and simple.
It seemed to me the obvious type for holding this collection of
unique objects was a Set, so that's how I did it. The input-reading method
grabs a line of input, parses it, and creates a "Foo foo = new Foo()". If an
equivalent instance (as determined by equals()) is already present in the
set, I want to let the new one go out of scope. If not already present, I
want to add it. Still, simple and basic.
Here's where things go sideways: I also need to store a reference to 'foo' in
another new object. If this is the first time I've seen it, everything is
fine because I already have the reference and can add it to both places, e.g.
fooSet.add(foo);
bar.addFoo(foo);
But if it was already present in the Set, I'm left holding a reference to the
"temporary" copy which is about to go out of scope. I know there's an
identical copy already in the Set but there's no way to retrieve it in order
to add it to the Bar object.
Yup. What you want is a Set.canonicalize or
Set.getRepresentativeMemberOfThisEquivalenceClass method. There isn't one.
I think there should be. You could do it by iterating over the set and
looking for an object equal to your probe object, but that would be
horrible.
I've switched over to using
Map<Foo, Foo>
This is the right way to do it.
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.
Weeeell, yes and no. Your canonicalisation step is in fact taking
different objects (which happen to have the same value) and giving you one
particular object (the canonical one), so that looks like a job for a Map
to me.
How do you determine equality for these objects? If it's by some kind of
key, like an ID number or something, you could use a map<Key, Foo>, which
would seem a little less kludgey.
tom
--
Got a revolution behind my eyes - We got to get up and organise