Addresses of Objects

I am trying to find a way of differentiating between two objects in Java. I am aware that the hashCode method will return an integer relating to the object's address providing that it has not been overridden. However since this is not guaranteed, after many hours googling I found the System.identityHashCode(Object obj) method where obj is the object of which the hashCode is required.

Is this the only method of differentiating between two objects, or is there a way of obtaining the actual address of an object?



  • Hi Adam

    You don't need address of an object in Java. Java is much more simple than C or CPP. For differentiating between two objects, you can use Object.equals(Object obj) method. Refer API available for JDK for more information.

    For example

    int x; long y;

    x.equals(y) // this will return false.
  • Hi,

    Thanks for your reply, but the equals method isnt any good for what Im trying to do. Im aiming to have the an identifier (either address of or unique integer) for an object appear in a tooltip and the user can then just check if two objects are the same.

    So far the System.identityHashCode(Object) method is working (to some extent), however it gives different results for primitive types. More clearly, if I have two objects A and B in a collection, with A having a field to store a reference to B then both B in the collection and the reference to B in A have the same identifiers. (Expected since they both point to the same object.) However looking at fields of B (primitive types only) they have different identifiers, although i would expect them to be the same since they belong to the same instance of B.

  • Sorry I am confused of your reply. Will you send a complete or clear situation where you stuck.
  • You cannot have references for primitive data types like int,float and double it should work with String though and StringBuffer. Hope that helps, I'm still learning but I know that the compilers just substitute the variable name with the value for primitve and the variables DON'T POINT TO OBJECTS.
Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!