I am developing a game on Android that involves a grid of objects. Right now I am using an array to store the objects, like this:
public class ObjectBuffer {
private final Object[] buffer;
private final int playfieldWidth;
ObjectBuffer(int playfieldWidth, int playfieldHeight) {
super();
this.buffer = new Object[playfieldWidth + (playfieldHeight * playfieldWidth)];
this.playfieldWidth = playfieldWidth;
}
public static int getX(int id) {
return id % playfieldWidth();
}
public static int getY(int id) {
return id / playfieldWidth();
}
public Object get(int id) {
return this.buffer[id];
}
public Object get(int x, int y) {
return this.buffer[x + (y * this.playfieldWidth)];
}
}
But, my questions is, is this the best way to accomplish this? I chose an array (as opposed to a list, ArrayList, or some other container) because once the width and height of the playfield are set, they do not change. The objects are there for state, and once they are instantiated and added to the array, they may be updated, but are not rearranged.
My question is similar to Storing objects for locating by x,y coordinates, but different enough that I wanted to ask my question separately. My requirements are different from his, and I don't think that a spatial index would be warranted in this situation. Please correct me if I'm wrong.
I should also mention, the array's dimensions will usually be 10x10 (100 elements), but may need to be able to accommodate a modest increase; but will not need to handle more than about a 15x15 grid (225 elements). These dimensions will always be known when generating the grid. After the grid has been generated, the dimensions will not change.