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 )
what is internal address , is it heap address or what ?
It doesn't really matter. The hash code doesn't actually represent anything - it's just a number that's used by hashing algorithms like the one used by HashSet. The only thing that's important is that it's consistent with equals, but the algorithm works best if non-equal objects have different hash codes.
They really have to remove that from the API doc, as we seem to have an extraordinary amount of beginners who think they can reverse engineer the heap address from the identity hashcode. And it simply can't be done.
It's probably less important how the integer is created (although you can always look at the source code), and more important that it is unique for objects that are supposed to be unique, and the same for objects that are supposed to be the same.
Joshua Bloch's "Effective Java" has an excellent section using & generating hash codes. Again, less useful for deciphering a Java SE object's hash code, and more useful for knowing when to override an object's hashCode() method, and things to keep in mind when overriding it.
In preparing for battle I have always found that plans are useless, but planning is indispensable. -- Dwight D. Eisenhower
Pete Nelson wrote:..., and more important that it is unique for objects that are supposed to be unique, and the same for objects that are supposed to be the same.
The only thing that is really important is that it is the same for objects that are equal. It (functionally) doesn't matter that the hash codes of two objects that are not equal are the different or not. This would be a valid implementation of hashCode for any class:
It wouldn't be very efficient though, a HashSet would put all instances of such a class in the same bucket, which would make it inefficient to find objects in the set.
Henry Wong wrote:They really have to remove that from the API doc, as we seem to have an extraordinary amount of beginners who think they can reverse engineer the heap address from the identity hashcode. And it simply can't be done.
And furthermore it shouldn't be. A major part of the philosophy behind Java is that you shouldn't need to know about this stuff.
@naveen: You're in Java now, not C/C++; and Java has references, not pointers. Furthermore, the designers have gone to great lengths NOT to tell you exactly what they are, beyond the fact that they allow the language to locate objects for you. Unless you plan on writing a compiler or a garbage collector any time soon, you really don't need to know how they work; and any programs you write that rely on assumptions of yours will be brittle, and may well get invalidated by a future change to the memory model.
Isn't it funny how there's always time and money enough to do it WRONG?