I'm currently working on a TD game with a map editor. Now obviously, you can save and load these maps (or should be able to, at least).
Problem is: at some point I'm calling .get()
on a HashMap
. Unfortunately, the keys that should be the same (logic-wise) are not the same object (in terms of reference), and, according to my previous google research, overriding their .equals
method isn't sufficient, since they still return different hashes with .hashCode()
(I verified that, they DO return different hashes, while .equals
does return true).
(On a side note, that's rather confusing, since the javadoc of HashMap.get(key)
only states that they have to be equal)
More specifically, the HashMap
contains instances of a class Path
of mine as keys, and should return the corresponding list of enemies (= value).
short version of Path
(without getters etc.):
public class Path
{
private List<Tile> tiles = new ArrayList<>();
@Override
public boolean equals(Object obj) {
//code comparing the two paths
}
@Override
public int hashCode() {
//what I still need to implement. ATM, it returns super.hashCode()
}
}
public class Tile
{
private int x;
private int y;
//constructor
//overrides equals
//getters & some convenience methods
}
Now if two Paths are equal, I'd like them to return the same hash code, so that the HashMap
returns the correct list of enemies. (I'll make sure not two identical paths can be added).
Now my question:
Do you suggest
- using some external library to generate a hash
- that I write my own implementation of calculating a hash, or
- something else
?
Note that I'd prefer to avoid changing the HashMap
to some other type of map, if that would even help solve the problem.