1

ok so im making my own Matrix class. and i have a transpose method that transposes a matrix. this is the block in the main method

    Matrix m1 = new Matrix(4,2);
    m1.fillMatrix(1,2,3,4,5,6,7,8);
    System.out.println("before " + m1.toString());
    m1.transpose();
    System.out.println("after " + m1.toString());

this is where it gets messed up, at m1.transpose(); in the transpose() method

public Matrix transpose() {
    if(isMatrix2) {
        Matrix tempMatrix = new Matrix(row, col); // matrix2 contents are emptied once this line is executed
        for(int i=0; i < row; i++) {
            for(int j=0; j < col; j++)
                tempMatrix.matrix2[i][j] = matrix2[i][j];
        }

so for some reason, the tempMatrix.matrix2 has the same id as this.matrix2. so when the codes executes

 Matrix tempMatrix = new Matrix(row,col);

then the contents of this.matrix2 is emptied. anyone know what might be going on here? the fields are all private static, if that helps...

user1459976
  • 207
  • 6
  • 14
  • 1
    What is `isMatrix2`?? And what is `matrix2`? – Rohit Jain Oct 18 '12 at 05:06
  • 1
    Can please you show the constructor for `Matrix`? I wonder if you're accidentally using static variables somewhere... – Paul Bellora Oct 18 '12 at 05:15
  • isMatrix2 is a boolean and matrix2 is a 2d array of ints... it doesnt matter what they are, its that something is happening to the contents of matrix2 when i dont touch it, or so i think. @ Paul, yes i mentioned in my op that all fields are declared as private static – user1459976 Oct 18 '12 at 05:15
  • thank you Paul, i changed all the fields so they are just private instead of private static. i dont understand why that would make a difference, but it did. it works fine now – user1459976 Oct 18 '12 at 05:32
  • 2
    @user1459976 If you declare a field `static` then all the instances that field. So, `matrix2` becomes common for all instances. So, when it becomes `empty` for tempMatrix, the change will be reflected to all instances. – Rohit Jain Oct 18 '12 at 05:33
  • oh right, that clears things right up. thanks for the explanation Rohit – user1459976 Oct 18 '12 at 06:00

0 Answers0