What I want to achieve: I need to obtain a run time (unique) id for "any object" (for classes either in java SE, classes I have created or classes provided by other third parties... any instance of a class).
Ideally it should be as easy as:
Map<Object, UUID> objId = new HashMap<>();
MyClassFoo foo = new MyClassFoo();
UUID fooId = objId.getOrElse(foo, UUID.randomUUID());
if (!objId.containsKey(foo)) {
objId.put(foo, fooId);
}
// From here onwards whenever I need the runtime ID for foo I can get it from the map objId
The problem:
This won't work for mutable objects since my object can keep changing hence its hash code, and we all know the problems that would/may introduce when working with a map using a mutable object as key.
Besides such approach does not work due to the limitations like: you cannot use an ArrayList as a key if the ArrayList is a List of Lists containing itself, since the map will attempt to use its hashCode. The implementation of hash code for ArrayList requires calculating the hashCode of all its contained objects causing a stack overflow for self-contained lists.
What I need from the community:
I need to know the most (or a couple of good proposals for alternatives to that map) efficient way to achieve what I want. I've considered a sorted List<Pair<Object, UUID>>
and do some binary search on it whenever I need the id for an object, but besides making the implementation a bit more complex I'm also worried about the performance impact of such change (given that such list may contain from a few couple of objects up to several million).
Have I done my homework? I think so, besides considering possible alternatives (as the one mentioned above) I tried to find a different implementation of a map that fulfills my needs, but all of them seem to use the hashCode of the key object.
Is this an opinion based question? Well... yes, but I wouldn't like it to be labeled as such since what I am requesting are alternatives to solve my issue and the performance implication/aspects to consider for the implementation of such proposals.
P.S: I am working in the Java language but the concept of the problem can be applied independently of that.
System.identityHashCode()
for itshashCcode()
implementation, and==
for itsequals()
, then use the map to associate this object with a unique identifier. You'd of course also need to useWeakReference
s to prevent out-of-memory conditions.