Например так:
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
Использование
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"));
}
}
Вывод
true
false
null