Asking for the best solution always implies an uncomfortable pressure. And in order to properly answer such a question and really give the best solution, one requires a degree of detail in the problem specification that is hard to Conway.. eh.. convey on a Q&A site.
But not only because of the difficulties in answering this question, I'd recommend to model this as an interface in the first place. Assuming you already have a Cell
interface, you could represent the World as a
interface World {
Cell get(int x, int y);
int getSizeX();
int getSizeY();
}
Depending on the trade-off between memory consumption and efficiency, you can then offer various implementations. For a "dense" (and very efficient) implementation, you can use arrays:
class ArrayWorld implements World {
private Cell cells[][] = ...
@Override
public Cell get(int x, int y) {
return cells[x][y];
}
...
}
For a "sparse" (although slightly less efficient) implementation, you might use something like a
class MapWorld implements World {
// Assuming a class "IntPair" which encapsulates
// two int values, with proper implementation
// of hashCode and equals:
private Map<IntPair, Cell> map = new HashMap<IntPair, Cell>();
@Override
public Cell get(int x, int y) {
return map.get(new IntPair(x,y));
}
...
}
The neat thing here is that you may easily implement a property of the world that is frequently used in such cellular automata: Namely, a world with a "torus" topology, where the coordinates are "wrapping" at the borders:
class TorusWorld implements World {
private World delegate = ...
@Override
public Cell get(int x, int y) {
int wrappedX = ((x % getSizeX()) + getSizeX()) % getSizeX();
int wrappedY = ((y % getSizeY()) + getSizeY()) % getSizeY();
return delegate.get(wrappedX, wrappedY);
}
}
This "Torus world" can then be backed by any other implementation of the World
interface.
However: You also mentioned an Animal
class, so it's not entirely clear what your Cell
class should look like: Will the Cell
really contain an Animal
? Or only a set of flags that show whether the cell contains Food, a Prey or something else? Will it be possible that the Cell contains two things (e.g. a Predator and Food, which probably will not interact)? These are all the questions that should be answered as early as possible, during the specification phase.