I have a World which can contain multiple Bullets, all of the Bullet has a Position (Center). Which basically is the following
class Position{
private double xCoordinate;
private double yCoordinate;
}
We need to implement a function in O(1)
(nearly constant time) which retrieves the corresponding bullet in the World by giving a position.
I've tried to use HashMap
to store the key/value
(Position/Bullet) paires. However, after change the coordinate of a Bullet, I am unable to retrieve this anymore using his updated Position like:
this.bullets.get(new Position(bullet.getX(), bullet.getY())))
gives null
as result
Initally, I thought that the problem was caused by the problem of hashCode and equals method I've implemented:
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (other == this) return true;
if ((other instanceof Position)) {
if (((Position) other).getXCoordinate() == this.getXCoordinate() &&
((Position) other).getYCoordinate() == this.getYCoordinate()) return true;
}
return false;
}
@Override
public int hashCode(){
return Objects.hash(this.getXCoordinate(),this.getYCoordinate());
}
But later, I realised that the datastructure I used is not suitable for this kind of problem. Namely, the Position
of the Bullet can change anytime, but the key in the bucket will however, not be updated.
I've searched for a while, but I cannot find a suitable datastructure to do that. So I want kindly ask if there is a good datastructure/ implementation that I can use to solve this problem in O(1)
time?