I Have the following two classes and want to use Foo1 as keys in a HashMap. Two Foo1 objects are equal if their Foo2 objects are equal, and Foo2 objects are equal if their byte arrays satisfy Arrays.equals().
I am not quite sure what to do for the hashCode() method for Foo1. Do I just need to sum up the hashcodes from each of its Foo2 objects or is this inefficient?
public class Foo1 {
Foo2[] foo2_array;
@Override
public boolean equals(Object Other) {
for (int i = 0; i < foo2_array.length; i++) {
if (!foo2_array[i].equals(other.foo2_array[i])
return false;
}
return true;
}
@Override
public int hashCode() {
// what to here?
}
}
public class Foo2 {
byte[] values;
@Override
public boolean equals(Object other) {
return Arrays.equals(values, other.values);
}
@Override
public int hashCode() {
return Arrays.hashCode(values);
}
}
Your
hashcodeshould use the same set of properties asequalsfor it not to break the contract.Just use the
Arrays.hashcodeas done inFoo2Also you dont have to loop through each element in your equals you can just use
Arrays.equalsFoo2 equals can look like this similar to Foo1.equals
and hashcode similar to Foo1 hashcode
Also while implementing equals do check for same reference and object validity for null.