I have an object array called Position[] that returns an array of Position objects. I would like to use this as my key for a hashmap for the following: HashMap<Position[],Double> h = new HashMap<>();
I understand that arrays have different hashcodes even if the elements are the same. So I went ahead and tried to override the equals and hashcode. This was my attempt:
public class Key {
private Position p1;
private Position p2;
public Key(Position p1, Position p2){
this.p1 = p1;
this.p2 = p2
}
@Override
public boolean equals(Object object) {
if (!(object instanceof Key)) {
return false;
}
Key newKey = (Key) object;
return this.hashCode()== newKey.hashCode(); //bit of a hack way
}
@Override
public int hashCode(){
int result = 17;
result = 31 * result + this.p1.hashCode();
result = 31 * result + this.p2.hashCode();
return result;
}
}
So I had to change my map to HashMap<Key,Double> However, when ever i go to get the value using the key is still returns null.
An example of what can be passed into they constructor of Key are G2 G4 or E4 E6 ETC.
How would I go about achieving this so that the comparisons actually work?
Thanks.
this.hashCode()== newKey.hashCode()← That will fail eventually. Just use aList<Position>instead of an array. Arrays don’t have useful hash codes, but Lists are guaranteed to have hash codes based on their elements’ hash codes.Listinstead of arrays, you can get the correct hashcode using the utility class method Arrays.hashCodeArrayList<Position>possible? or doe sit have to beList<Position>