Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What data structure is most suitable for implementing a 2-D array in Java?

I want to implement a 2-D array kind of a thing.

What data structure will be most suitable for this? An array or some other data-structure will do. If there is any other data structure which will satisfy my requirement, then please tell me.

I don't want to use an array because the 2-D array needs to be declared early in the program but it is not fixed; the size will be determined at run time.

Also, the number of rows will be equal to the number of columns; this is fixed, because the same name will be given to both the rows and the columns.

I also want to traverse through this 2-D data structure as I would through a Map.

like image 995
AGeek Avatar asked Mar 26 '09 03:03

AGeek


2 Answers

It sounds like you want to use a row-key, a col-key, and then the value at that location. There's no builtin data structure that'll do that for you.

The easiest thing to use may be a 2d array for the actual data. Use something like the following to go from a row or column name to the actual index in your array. Add as many name-to-index bindings as you want.

Map<String, Integer> rows = new HashMap<String, Integer>();
Map<String, Integer> cols = new HashMap<String, Integer>();

Then getting that value in the grid...

grid[rows.get("Row name")][cols.get("Column name")];

Put the grid and a get(String rowName, String colName) method in a class if you want a cleaner API.

Edit: I see the question has been updated, and it looks like the name-to-index pairs are the same for both rows and columns. So here's an updated version:

class SquareMap<V> {
    private V[][] grid;
    private Map<String, Integer> indexes;

    public SquareMap(int size) {
        grid = (V[][]) new Object[size][size];
        indexes = new HashMap<String, Integer>();
    }

    public void setIndex(String name, int index) {
        indexes.put(name, index);
    }

    public void set(String row, String col, V value) {
        grid[indexes.get(row)][indexes.get(col)] = value;
    }
    public V get(String row, String col) {
        return grid[indexes.get(row)][indexes.get(col)];
    }
}
like image 114
Nikhil Avatar answered Sep 28 '22 07:09

Nikhil


(Edits based on comment)

If the size is determined at runtime that is not an issue. This might work:

final int[][]              data;
final int                  size;
final Map<String, Integer> names;

// code that sets the size variable
names = new HashMap<String, Integer>();
data  = new int[size][size];

names.put("ID-A", 0);
names.put("ID-B", 1);

data[names.get("ID-A")][names.get("ID-A")] = 39;
data[names.get("ID-A")][names.get("ID-B")] = 40;
data[names.get("ID-B")][names.get("ID-A")] = 41;
data[names.get("ID-B")][names.get("ID-B")] = 42;
like image 35
TofuBeer Avatar answered Sep 28 '22 08:09

TofuBeer