Your task is to complete the implementation of a generic Matrix class. A matrix is a two-dimensional arrangement of elements. You access elements with a row and column index. For example,

Matrix<String> tttBoard = new Matrix<String>(3, 3);
tttBoard.put(0, 0, "x"); if (tttBoard.get(1, 2).equals("o")) . . .

If the matrix has many rows and columns but few elements, it doesn't make sense to allocate a large two-dimensional array, most of whose entries are null. Instead, we will only store the non-null entries in a map. Keys of the map are integer pairs. A Pair class is provided for you.

Complete the implementations of the get and put method below.

Complete the following file:

import java.util.Map; import java.util.HashMap; public class Matrix<T> { public Matrix(int rows, int columns) { elements = new HashMap<Pair<Integer, Integer>, T>(); } // add your get and put methods here private Map<Pair<Integer, Integer>, T> elements; // the following method is used to check your work public static String check(int r, int c, String s) { int rows = 3; int columns = 4; Matrix<String> m = new Matrix<String>(rows, columns); // add letters of s diagonally for (int i = 0; i < s.length(); i++) { m.put(r, c, s.substring(i, i + 1)); r++; if (r >= rows) r = 0; c++; if (c >= columns) c = 0; } // make string representing matrix content String t = ""; for (int i = 0; i < rows; i++) for (int j = 0; j < columns; j++) if (m.get(i, j) == null) t += "."; else t += m.get(i, j); return t; } }

Use the following file:

public class Pair<T, S>
   public Pair(T firstElement, S secondElement)
      first = firstElement;
      second = secondElement;
   public int hashCode() { return 31 * first.hashCode() + second.hashCode(); }
   public boolean equals(Object otherObject)
      Pair other = (Pair) otherObject;
      return first.equals(other.first) && second.equals(other.second);
   public T getFirst() { return first; }
   public S getSecond() { return second; }
   private T first;
   private S second;