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()
.