I have a class in java which contains two integers and an array of integers as members and I want to make a hash map with the above object as key. How should i override the equals operator and hashCode() such that the object which have same Integer values as that of members and same entries in the array get the same Hash Code?(or is such a thing even possible) Thanks in Advance.
Use java.util.Arrays#equals(int[], int[]) and Arrays.hashCode(int[])
To calculate a hashcode for the int array you can use java.util.Arrays.hashcode(int[]).
If you look at its implementation:
public static int hashCode(int a[]) {
if (a == null)
return 0;
int result = 1;
for (int element : a)
result = 31 * result + element;
return result;
}
you can derive an idea how to calculate a hash code for your class which should be based on the values of your two integers and the integer array:
public class MyClass {
private int a, b;
private int[] array;
public int hashCode() {
return (31 * (31 * Arrays.hashCode(array) + a)) + b;
}
To equals implementation can look like:
public int equals(Object o) {
if (o instanceof of MyClass) {
MyClass m = (MyClass)o;
return m.a == a && m.b == b && Arrays.equals(m.array, array);
}
else
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With