hashCode () returns the value of the integer, not its hashCode

2

I have a matrix like this, from which I want to obtain the codes hash of all its elements:

Integer[][] { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 },    { 1, 2, 2 } };

I go through it with a loop and I do .hashCode() of each element. But instead of returning a different identifier number for each one, it gives me back its value (in all 1s the hashcode is equal to 1, in the 2s to 2 etc).

Why are not you giving me the hashCode?

    
asked by H. Postiga 10.03.2018 в 22:47
source

2 answers

3

The HashCode is not a unique object identifier in Java. The HashCode must fulfill only 3 conditions:

1 - It can not vary during the execution of the program, as long as the information used for comparisons equals() of the object is not modified.   2 - If two objects are equal, according to the use of the equals() method, then the HashCode of both objects must be the same.   3 - If two objects are different, according to the utilization of the equals() method, it is not necessary that their HashCode be different.

These HashCode are used for the optimization of search operations, especially in data structures that use hash tables to store their elements.

And how is it used? Well, simple. These structures store the data by grouping them according to their HashCode. Determining if the HashCode of the object is within a range of values, predefined by the implementation of the structure. Depending on this range of values, it is determined where to store the object. In this way, when you search within these structures, using the HashCode of the object you are looking for, you can determine exactly where you can find the object, reducing the search / access times considerably.

Because of the above I commented that the HashCode is not at all a unique identifier of instances of objects, and that all instances of the same object can perfectly have a different one each, except that they are the same according to the method equal() .

    
answered by 10.03.2018 / 23:25
source
3

This is normal in Java, the class Integer.class , the implementation of the method is simply the return of your value.

public int hashCode() {
  return value; 
}
  

Also on the Java documentation of hashCode () supports it,   where the returned value is the assigned primitive value.

    
answered by 10.03.2018 в 22:57