0

I'm implementing a set interface that requires my matrix to be immutable. I thought I had it correct but the test I'm running to change a value to 101 still changes that value.

public class NeilMatrix implements Matrix {
    private final int[][] data;

    private NeilMatrix(int[][] data) {
        this.data = data;
    }

    public int getElement(int y, int x) {
        return data[y][x];
    }

    public String toString() {
        String strMatrix = "";
        for(int i = 0; i < getRows(); i++) {
            for(int j = 0; j < getColumns(); j++) {
                strMatrix = strMatrix.concat(data[i][j] + " "); 
            }
            strMatrix = strMatrix.concat("\n");
        }
        return strMatrix;
    }

    /**
     * Entry point for matrix testing.
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int[][] data1 = new int[0][0];
        int[][] data2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int[][] data3 = {{1, 4, 7}, {2, 5, 8}, {3, 6, 9}};

        Matrix m1 = new NeilMatrix(data1);
        Matrix m2 = new NeilMatrix(data2);
        Matrix m3 = new NeilMatrix(data3);

        //check for reference issues
        System.out.println("m2 -->\n" + m2);
        data2[1][1] = 101;
        System.out.println("m2 -->\n" + m2);


    }
}

This is the relevant piece of code. Shouldn't marking it final be enough to make sure you can't change it? If not, how do I do that? Please note that I cannot change the class to be private or add the final keyword to it so the other post suggested isn't helpful.

Kendra
  • 125
  • 2
  • 12

0 Answers0