Sometimes it is handy to have a unique identifier for an object. By unique identifier, I mean an ID that represents a single instance of an object; not just an object that 'equals' another object, but the actual unique instance. A primary usecase would be during debugging when you have an object which has changed physically, and while being equivalent due to an overridden 'equals' and 'hashcode' method, is not the same object. Say, for instance, you are debugging a failing cache mechanism, and you are trying to track down when the physical instance changed.
The first reaction most developers have when trying to get a unique identifier to quickly identify when an object changes is to use the #hashcode
method of the object, which in the traditional Object
case is unique for each object (* in reality the specification doesn't enforce this rule; but most modern JVMs use a relationship to the object's memory location, so typically hashcode is unique). If the 'equals' method is overridden, and the developer of the class was responsible, 'hashcode' was overridden as well, so now, if implemented correctly, hashcode will return the same value for these two distinct objects, and your helpful debugging tool is gone.
Thankfully, you can still gain access to this value - simply use System.identityHashCode(Object)
, passing in the object you want the hashcode for. The value returned is always the same as if hashCode was not overridden.
Object x = getSomeObject(); System.out.println("Object Identifier: " + System.identityHashCode(x)); cache.cacheObject(x); // ... Object cachedX = cache.getObject(); System.out.println("Object Identifier: " + System.identityHashCode(cachedX));
So, while you shouldn't rely on this value to be unique in production code (if you need that kind of support, use the ID generator from this tip :)) - but if you're debugging and need a quick and easy object tracking mechanism on a Sun, IBM, or other mainstream VM, consider System.identityHashCode(Object).
Read full article from General: When Debugging Get a Unique Identifier For Any Object
No comments:
Post a Comment