In Java, the hashCode() method is a method of the Object class that is used to calculate a hash code value for an object. A hash code is a numerical value that is used to identify an object in a hash-based data structure, such as a hash table or a hash map.
By default, the hashCode() method returns a different value for each object, based on the object's memory address. However, you can override the hashCode() method in your own classes to provide a more meaningful hash code value based on the object's state.
Here is an example of how to override the hashCode() method in a class:
public class MyClass {
private int x;
private int y;
public MyClass(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + x;
result = 31 * result + y;
return result;
}
}Sourcwww:e.lautturi.comIn this example, the hashCode() method calculates a hash code value based on the values of the x and y fields of the MyClass object.