SimpleMatrixMultiplier implements MatrixMultiplier { @Override public <E extends Number> Matrix<E> multiply(Matrix<E> first, Matrix<E> second) { if (first.getColumns() != second.getRows()) { throw new IllegalArgumentException("Incompatible matrix dimensions"); } final Matrix<E> result = factory.getMatrix(first.getRows(), second.getColumns()); for (int row = 0; row < first.getRows(); row ++) { for (int column = 0; column < second.getColumns(); column ++) { multiplyRowByColumn(first, second, result, row, column); } } return result; } SimpleMatrixMultiplier();  SimpleMatrixMultiplier(MatrixFactory factory); @Override Matrix<E> multiply(Matrix<E> first, Matrix<E> second); static void multiplyRowByColumn(Matrix<E> first, Matrix<E> second, Matrix<E> result, int row, int column);  }
@Test public void testMultiplication() throws Exception { final Matrix<Integer> first = new ArrayMatrix<>(3, 2); first.set(0, 0, 2); first.set(0, 1, 3); first.set(1, 0, 0); first.set(1, 1, 4); first.set(2, 0, -1); first.set(2, 1, 5); final Matrix<Integer> second = new ArrayMatrix<>(2, 3); second.set(0, 0, 6); second.set(0, 1, 1); second.set(0, 2, 1); second.set(1, 0, 0); second.set(1, 1, 3); second.set(1, 2, 2); final SimpleMatrixMultiplier multiplier = new SimpleMatrixMultiplier(); final Matrix<Integer> multiplication = multiplier.multiply(first, second); assertThat(multiplication.getColumns(), is(3)); assertThat(multiplication.getRows(), is(3)); assertThat(multiplication.get(0, 0), is(12)); assertThat(multiplication.get(0, 1), is(11)); assertThat(multiplication.get(0, 2), is(8)); assertThat(multiplication.get(1, 0), is(0)); assertThat(multiplication.get(1, 1), is(12)); assertThat(multiplication.get(1, 2), is(8)); assertThat(multiplication.get(2, 0), is(-6)); assertThat(multiplication.get(2, 1), is(14)); assertThat(multiplication.get(2, 2), is(9)); }
@Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Incompatible matrix dimensions") public void testIncompatibleMatrices() throws Exception { final Matrix<Integer> first = new ArrayMatrix<>(3, 3); final Matrix<Integer> second = new ArrayMatrix<>(4, 4); final SimpleMatrixMultiplier multiplier = new SimpleMatrixMultiplier(); multiplier.multiply(first, second); }