Override the hashCode() method in a class
In this step, we will override the hashCode()
method in a class. Here, we create a MyClass
class with two float
variables a
and b
. We then override the hashCode()
method in the class and calculate the hash code of the object using the formula (31 * Float.floatToIntBits(a)) + Float.floatToIntBits(b)
.
import java.lang.Float;
class MyClass {
float a;
float b;
public MyClass(float a, float b) {
this.a = a;
this.b = b;
}
@Override
public int hashCode() {
return (31 * Float.floatToIntBits(a)) + Float.floatToIntBits(b);
}
}
public class FloatHashcode {
public static void main(String[] args) {
MyClass obj = new MyClass(2.3456F, -4.567F);
int hash = obj.hashCode();
System.out.println("Hash code for obj is " + hash);
}
}
To compile and run the file, execute the following commands in the terminal:
javac ~/project/FloatHashcode.java
java FloatHashcode