I made a vector set in order to avoid thrashing the GC with iterator allocations and the like ( you get a new/free each for both the set reference and the set iterator for each traversal of a HashSet's values or keys )
anyway supposedly the Object.hashCode()
method is a unique id per object. (would fail for a 64 bit version?)
But in any case it is overridable and therefore not guaranteed unique, nor unique per object instance.
If I want to create an "ObjectSet" how do I get a guaranteed unique ID for each instance of an object??
I just found this: which answers it.
How to get the unique ID of an object which overrides hashCode()?
The simplest solution is to add a field to the object. This is the fastest and most efficient solution and avoid any issues of objects failing to be cleaned up.
abstract Ided {
static final AtomicLong NEXT_ID = new AtomicLong(0);
final long id = NEXT_ID.getAndIncrement();
public long getId() {
return id;
}
}
If you can't modify the class, you can use an IdentityHashMap like @glowcoder's deleted solution.
private static final Map<Object, Long> registry = new IdentityHashMap<Object, Long>();
private static long nextId = 0;
public static long idFor(Object o) {
Long l = registry.get(o);
if (l == null)
registry.put(o, l = nextId++);
return l;
}
public static void remove(Object o) {
registry.remove(o);
}
No, that's not how hashCode()
works. The returned value does not have to be unique. The exact contract is spelled out in the documentation.
Also,
supposedly the Object.hashCode() method is a unique id per object
is not true. To quote the documentation:
As much as is reasonably practical, the
hashCode
method defined by classObject
does return distinct integers for distinct objects.
java.lang.System.identityHashCode(obj);
will do this for you, if you really need it and understand the repercussions. It gets the identity hashcode, even if the method to provide the hashcode has been overridden.
Trying to outperform the java GC sounds like premature optimization to me.
The GC is already tuned to handle small short-lived objects. If you have performance issues with GC, you ought to help the GC, not re-implement it (IMNSHO)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With