class Entity { static double r; double x, y; int cellX() { return (int)(x/r); } int cellY() { return (int)(y/r); } List neighbors() { List ans = new List(); int cx = cellX(), cy = cellY(); for(int xi=cx-1; xi<=cx+1; xi+=1) { for(int yi=cy-1; yi<=cy+1; yi+=1) { for(Entity e : grid[xi][yi]) { if (e != this && this.distanceFrom(e) < r) ans.add(e); } } } return ans; } void move(int newX, int newY) { grid[cellX()][cellY()].remove(this); this.x = newX; this.y = newY; grid[cellX()][cellY()].add(this); } } List[][] grid; grid = new List[width][height];