Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I get a unique ID per object in Java? [duplicate]

Tags:

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

like image 203
peterk Avatar asked Jan 20 '12 08:01

peterk


4 Answers

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);
}
like image 185
Peter Lawrey Avatar answered Oct 30 '22 18:10

Peter Lawrey


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 class Object does return distinct integers for distinct objects.

like image 35
NPE Avatar answered Oct 30 '22 16:10

NPE


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.

like image 6
Chris Dennett Avatar answered Oct 30 '22 17:10

Chris Dennett


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)

like image 2
Rolf Rander Avatar answered Oct 30 '22 16:10

Rolf Rander