Java – how to get a unique ID per object in Java?


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()?

Best Solution

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) {