Re: Get reference to object in Set



Tom Anderson wrote:
On Thu, 5 Mar 2009, Patricia Shanahan wrote:

I think this question has already been asked, but I have failed to work out a good search term to find the previous discussion.

Yes, i remember having a huge row on this group about it. Mind you, i could say that about a lot of things.

Aha, found it. Try searching this group for "1999 Nissan Quest" :).

Yes, that's the thread I was thinking of.


Suppose I have a Set<MyType> mySet and a MyType myObject. mySet.contains(myObject) is true. I need a reference to the equal object that is already in mySet.

Currently, I do this by maintaining a Map<MyType,MyType>. When the get call returns null I do a myMap.put(myObject, myObject), so that future get calls with equal objects will return the actual reference.

Is there a better way to handle this? Any way to make a Set return a reference to the object it contains?

Sadly not. A map seems to be the only way.

One of the ideas that came up was using a map not from MyType to MyType, but from SomeTypeContainingTheUniquelyIdentifyingAttributesOfMyType to MyType. I don't know if that's applicable in your case.
....

I don't think so. I have several different classes, each with their own
equality rules. All the classes in question implement an interface,
Child, that relates to how I hook them together to form a forest. That
interface is the only thing the objects all have to have in common.

In that situation, Map<Child,Child> is the way to go if I need a map.

Patricia
.