Anurag Sanyal
Anurag Sanyal

Reputation: 43

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.

Upvotes: 3

Views: 1564

Answers (3)

Clashsoft
Clashsoft

Reputation: 11882

You can check for array equality using the java.util.Arrays class:

int[] array1 = { 1, 2, 3 };
int[] array2 = { 1, 2, 3 };

boolean equal = Arrays.equals(array1, array2) // --> true

To calculate the hash code of an array, the same class can help you out as well:

int hash = Arrays.hashCode(new int[] { 1, 2, 3 })

Note that the class has overloaded methods for all array types - including Object[].

Upvotes: 0

wero
wero

Reputation: 32980

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;
    }

Upvotes: 2

erosb
erosb

Reputation: 3141

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

Upvotes: 4

Related Questions