Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding the hashCode( ) in java for a class that contains an array

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.

like image 752
Anurag Sanyal Avatar asked Mar 14 '26 07:03

Anurag Sanyal


2 Answers

Use java.util.Arrays#equals(int[], int[]) and Arrays.hashCode(int[])

like image 104
erosb Avatar answered Mar 16 '26 20:03

erosb


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;
    }
like image 28
wero Avatar answered Mar 16 '26 19:03

wero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!