There are probably many ways that you could go about this. Most of which are not known to me. However I have recently solved a similar problem in two different ways:
Two Dimensional Array
Implementing the "Map" as a two Dimensional Array is the obvious solution. Most likely for this scenario you will want an List
implementation so that you can resize easily. It will however require nested loops and such to search for a particular location, and the indexes might become somewhat confusing.
Map
A (in my opinion) better way to solve this problem would be to use a Map
. You should create a Position
class that has two variables (or three for a three-dimensional map) that record the X and Y position (Make sure you also implement the equals()
and hashCode()
methods). You can then use a Position
object as the key in a Map
implementation, stored against instances of Animal
. This will allow for faster searching of a particular location (see HashMap vs ArrayList performance am I correct), and tidier code, ie no nested loops when iterating over the whole map. You can loop over the whole map like this:
for(Map.Entry<Position, Animal> entry : animalMap.getEntries()){
//Do stuff
}
A couple of years ago I saw a tutorial project that implemented a Fox/Rabbit simulation. You may want to have a look at that for some ideas: http://www.bluej.org/objects-first/
You need to download the "Book Projects" .zip file. The relevant project is in Chapter 10.