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);
}