Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapper class strange behaviour in java

Tags:

java

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?

like image 240
user3790666 Avatar asked Mar 18 '23 20:03

user3790666


1 Answers

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)
like image 88
adarshr Avatar answered Apr 06 '23 04:04

adarshr