I'm using this class so that objects can find other objects that are near them.  Each object has a position and radius. Objects are added to the Grid. If they move then they call update with their new position.  An object can call retrieve to find which objects are around it. How can I optimize it, specifically the retrieve function?import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;import java.util.Arrays;public class Grid {    private Map<Integer, Set<Obj>> objects = new HashMap<>();    private Set<Obj> retrievedObjects = new HashSet<>();    float size;    int divisions;    public Grid(float size, int divisions) {        this.size = size;        this.divisions = divisions;    }    public void update(Obj obj) {        if (!obj.grids.equals(getGridsObjIsIn(obj.position, obj.radius))) {            remove(obj);            insert(obj);        }    }    public void insert(Obj obj) {        obj.grids = getGridsObjIsIn(obj.position, obj.radius);        for (Integer grid : obj.grids) {            if (objects.containsKey(grid)) {                objects.get(grid).add(obj);            } else {                objects.put(grid, new HashSet<Obj>(Arrays.asList(obj)));            }        }    }    public void remove(Obj obj) {        for (Integer grid : obj.grids) {            objects.get(grid).remove(obj);        }        obj.grids.clear();    }    public Set<Obj> retrieve(Vector2 pos, float radius) {        retrievedObjects.clear();        Set<Integer> grids = getGridsObjIsIn(pos, radius);        for (Integer grid : grids) {            if (objects.containsKey(grid)) {                retrievedObjects.addAll(objects.get(grid));            }        }        return retrievedObjects;    }    private Set<Integer> getGridsObjIsIn(Vector2 pos, float radius) {        Set<Integer> grids = new HashSet<>();        int[] min = positionToGrid(pos.x - radius, pos.y - radius);        int[] max = positionToGrid(pos.x + radius, pos.y + radius);        for (int x = min[0]; x <= max[0]; x++) {            for (int y = min[1]; y <= max[1]; y++) {                grids.add(x + y * divisions * divisions);            }        }        return grids;    }    private int[] positionToGrid(float x, float y) {        return new int[]{Math.round(divisions / size * x), Math.round(divisions / size * y)};    }}
Spatial grid of objects
java;game