Reputation: 1940
I searched the questions, but not found any satisfactory answer.
In Cpp/C++, I can use the object address to check the two objects address to say that the two objects are the same or it is the different objects but with same value.
In python, I could use the id method to get each object ID
In java, is there any method that not needs re-implement hashCode()
to do this?
I suppose that may according to JVM, the objects may be released and recycled next time, so there is no such method in java? am I right?
Upvotes: 2
Views: 667
Reputation: 46960
I didn't intend to try an answer here, but a correction is needed. The actual wording in the documentation is:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
This provides no guarentee that hashcodes are unique, only that the implementation tries to make them unique. Moreover, it stands to reason that if a 64-bit physical address (for a 64-bit JVM) is folded into a 32-bit hash value, there must be aliasing, in fact 4 billion aliases for each hash value.
The Java API specifically avoids giving access to physical addresses because it wishes to allow JVMs to use copying collectors, where the physical address of an object can change at any time.
Even for a 32-bit JVM, if there is a copying collector and the hash for an object is calculated from its address at creation time, then that object is copied to a different generation (as normally occurs), the same hash might well be calculated for a different new object created in the same place of the ephemeral (young) generation.
No doubt Java doesn't provide unique id's by default due to the performance overhead. It's simple to implement them yourself with a static counter to assign unique ids in the respective constructor if they're needed.
interface ObjectWithUniqueId {
public long getId();
}
class BaseObjectWithUniqueId implements ObjectWithUniqueId {
private static long currentId = 0;
private final long id;
// TODO Synchronize me if we are in a multithreaded environment!
public BaseObjectWithUniqueId() { id = ++currentId; }
public long getId() { return id }
}
Upvotes: 3
Reputation: 136042
The answer is no. According to Object.hashCode API the hashCode method defined by class Object does return distinct integers for distinct objects
. If even Object.hashCode was based on the object address it would not guarantee uniqueness because Java objects can be moved on the heap by GC.
Upvotes: 2