Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming a 2D grid in Java

What is the best data structure to use when programming a 2-dimensional grid of tiles in Java? Tiles on the grid should be easily referenced by their location, so that neighbors and paths can be efficiently computed. Should it be a 2D array? An ArrayList? Something else?

like image 607
Matthew Piziak Avatar asked Jun 17 '11 16:06

Matthew Piziak


3 Answers

If you have a fixed dimension for your grid, use a 2D array. If you need the size to be dynamic, use an ArrayList of ArrayLists.

like image 29
Ted Hopp Avatar answered Sep 30 '22 15:09

Ted Hopp


If you're not worrying about speed or memory too much, you can simply use a 2D array - this should work well enough.

If speed and/or memory are issues for you then this depends on memory usage and the access pattern.

A single dimensional array is the way to go if you need high performance. You compute the proper index as y * wdt + x. There are 2 potential problems with this: cache misses and memory usage.

If you know that your access pattern is such that you fetch neighbours of an element most of the time, then mapping a 2D space into a 1D array as described above may cause cache misses - you want the neighbours to be close in memory, and neighbours from 2 different rows are not. You may have to map your 2d tiles in a different order to your 1d array. See Hilbert curves for example.

For better memory usage, if you know that most of your tiles are always the same (e.g. always grass), you might want to implement a sparse array or a quad tree. Both can be implemented quite efficiently, with cache awareness in mind (the sparse array link is good example for this). Another benefit is that these can be dynamically extended. However, you will always have to pay extra levels of indirection in the end for this to work.

NOTE: Be careful with using generic classes such as HashMaps with the key type being some primitive type or a special location class if you're worried about performance - you will either have to allocate an object each time you index the hash map or pay the price of boxing/unboxing. In addition to this, hash maps will not allow you efficient spatial queries (e.g. give me all objects existing in the radius R of a given object - quad trees are better for this).

like image 120
axel22 Avatar answered Sep 30 '22 14:09

axel22


A 2D array seems like a good bet if you plan on inserting stuff into specific locations. As long as its a fixed Size.

like image 39
RMT Avatar answered Sep 30 '22 14:09

RMT