jiaweizhang
jiaweizhang

Reputation: 819

Storing 2D Grid of objects

I am creating a game where I have a 2D grid of Tile objects. Each of these Tile objects have a number of instance variables containing objects like Tower and View.

I am currently implementing this grid as a HashMap from Point (awt) to Tile object. Is this a good way of implementing the grid? This allows me to not map certain points that don't have a Tile object yet.

The alternative would be to have a Tile[][], but that would require enough memory to be pre-allocated for the entire grid, even if no tile exists, right?

Both of these are also stored on the heap but I'd like to know performance/space differences between the two implementation.

Upvotes: 0

Views: 700

Answers (1)

Paul Boddington
Paul Boddington

Reputation: 37645

Both solutions (HashMap<Point, Tile> and new Tile[200][200]) would work. I think I'd go for the simpler solution (the array) unless you have very good reason to think memory is an issue. You are correct that new Tile[200][200] allocates memory for the entire grid even if there are no Tiles. Remember HashMap requires a lot of memory as each key/value pair is wrapped in an Entry object, so the map solution may not save memory unless the grid is sparse.

Upvotes: 1

Related Questions