T
T
Tarasov Konstantin2014-05-22 18:48:32
Java
Tarasov Konstantin, 2014-05-22 18:48:32

How to make a two-dimensional matrix with access not through int indices, but through String?

In general, the task is this, you need to make a two-dimensional matrix, but access to its elements should be done not through integer indices, but through rows. For example, matrix.get("col", "row"); Naturally, the usual array of arrays [][] is not suitable, you need to stir up something with collections.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mrstrictly, 2014-05-23
@saroff

Take a ready-made, efficient and debugged solution from Guava: https://code.google.com/p/guava-libraries/wiki/New...

V
verwolfdotss, 2014-05-22
@verwolfdotss

For example like this:

class Matrix<K, E> {
    private final Map<K, Integer> rowsMap = new HashMap<K, Integer>();
    private final Map<K, Integer> colsMap = new HashMap<K, Integer>();
    private final Object[][] matrix;

    Matrix(K[] rows, K[] cols) {
        matrix = new Object[rows.length][cols.length];
        for (int i = 0; i < rows.length; i++) {
            if (rowsMap.containsKey(rows[i])) throw new IllegalArgumentException("Row names should be unique");
            rowsMap.put(rows[i], i);
        }
        for (int i = 0; i < cols.length; i++) {
            if (colsMap.containsKey(cols[i])) throw new IllegalArgumentException("Column names should be unique");
            colsMap.put(cols[i], i);
        }
    }

    public E get(K row, K col) {
        Integer r = rowsMap.get(row);
        Integer c = colsMap.get(col);
        if (c == null || r == null) throw new NoSuchElementException();
        return (E) matrix[r][c];
    }

    public void set(E val, K row, K col) {
        Integer r = rowsMap.get(row);
        Integer c = colsMap.get(col);
        if (c == null || r == null) throw new NoSuchElementException();
        matrix[r][c] = val;
    }
}

K = key
E = element
Usage
public class Main {
    public static void main(String[] args) {
        Matrix<String, Boolean> m = new Matrix<String, Boolean>(
                new String[] {"cat", "dog", "raccoon"},
                new String[] {"domestic", "wild", "shady"}
        );
        m.set(true, "cat", "domestic");
        m.set(false, "dog", "wild");

        System.out.println(m.get("cat", "domestic"));
        System.out.println(m.get("dog", "wild"));
        System.out.println(m.get("raccoon", "shady"));
    }
}

Conclusion
true
false
null

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question