4
public class Test {
    public static void main(String args[]) {
        int i = 10;
        Integer a = new Integer(i);
        System.out.println(a);        //tostring method overriden
        System.out.println(a.hashCode());
    }
}

Output:
10
10

now my question is why hashCode() method is overriden in this case. If I want to find the object reference of the wrapper class object a in the above code. How do i do it?

Mandar Pandit
  • 2,171
  • 5
  • 36
  • 58
user3790666
  • 301
  • 3
  • 11
  • Maybe that is what you are looking for http://stackoverflow.com/questions/909843/java-how-to-get-the-unique-id-of-an-object-which-overrides-hashcode – Seega Aug 05 '14 at 12:55
  • What will you do by getting a reference. Just FYI `Integer` objects are immutable in Java. You cannot modify it once they are created. – Rahul Bobhate Aug 05 '14 at 12:56

3 Answers3

5

The object reference to the integer in your case is a. Unlike C, in Java, you can't get a reference pointer to an object. The hashCode is not used to identify the address location of an object in the memory.

From the hashCode API,

Returns a hash code value for the object. This method is supported for the benefit of hash tables such as those provided by HashMap.

As it turns out, the most efficient value of hashCode for an integer is the value itself.

If you still want to get hold of the original hash value of the object, I would suggest using the System.identityHashCode method.

System.identityHashCode(a)
adarshr
  • 61,315
  • 23
  • 138
  • 167
1

my question is why hashCode method is overriden in this case

Wrappers, like String, are immutable. Said this, if every different object of a class has a different value (state), that value is a perfect hash code: zero collisions, total entropy, homogeneus distribution...

If i want to find the object reference of the wrapper class object a in the above code.How do i do it?

Using System.identityHashCode()

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
1

In Java, hashcode helps to give a quick comparaison hint between two objects. As two different Integer having same value are equal, they should have same hash. That's the reason why the value was taken for hash.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252