I have a collection of objects, let's call them A, B, C, D,... and some are equal to others. If A and C are equal, then I want to replace every reference to C with a reference to A. This means (a) object C can be garbage collected, freeing up memory, and (b) I can later use "==" to compare objects in place of an expensive equals()
operation. (These objects are large and the equals()
operation is slow.)
My instinct was to use a java.util.Set
. When I encounter C I can easily see if there is an entry in the Set
equal to C. But if there is, there seems to be no easy way to find out what that entry is, and replace my reference to the existing entry. Am I mistaken? Iterating over all the entries to find the one that matches is obviously a non-starter.
Currently, instead of a Set
, I'm using a Map
in which the value is always the same as the key. Calling map.get(C)
then finds A. This works, but it feels incredibly convoluted. Is there a more elegant way of doing it?