1

I have a game with a 100 by 100 2d grid.

I have placed objects in some of the squares. If I wanted the user to be able to get something from a specific square, would it be better (use less cpu) to search trough each object every time or to have a object for each tile and a object array in which I can just find the object by using objectArray[x][y]

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
WEPIOD
  • 53
  • 9

3 Answers3

0

Use the array (Or some kind of HashMap). It is a O(1) access.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
0

If you would like to find an object in O(1) time, and you have an (x,y) pair of its location in the grid, nothing is going to beat a 2D array of objects, because there is no search going on. A 100×100 grid is tiny by modern standards, so it is a very good use of memory to speed things up.

If you would like to start with an object and find its coordinates on the grid, the quickest approach is to store the coordinates on the object itself, assuming that an object can be only on one square at any single time.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

Your grid of 100×100 is relatively small, so a 2D array is the way to go.

If your grid is large and sparsely populated, a Map<Point, MyObject> is a better solution, where Point has x and y coordinates. This will still allow very fast lookup of the object, without having to scan all objects sequentially.

If you implement your own Point class, remember to implement equals() and hashCode(), e.g. something like this:

public final class Point {
    private final int x;
    private final int y;
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return this.x;
    }
    public int getY() {
        return this.y;
    }
    @Override
    public String toString() {
        return "(" + this.x + "," + this.y + ")";
    }
    @Override
    public int hashCode() {
        return this.x * 127 + this.y;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj instanceof Point) {
            Point that = (Point) obj;
            return (this.x == that.x && this.y == that.y);
        }
        return false;
    }
}
Andreas
  • 154,647
  • 11
  • 152
  • 247