0

While I was working on some Java code, I figured that there might be something different between these 2 codes.
I know that they have the same functionality, but I think there is something different between them under the hood.

This is the first code:

int[][] MainMatrix = new int[2][2];
int[][] A = new int[2][2];
MainMatrix[0][0]=100;
MainMatrix[0][1]=200;
MainMatrix[1][0]=300;
MainMatrix[1][1]=400;


A=MainMatrix;

And this is the second one:

int[][] MainMatrix = new int[2][2];
int[][] A = new int[2][2];
MainMatrix[0][0]=100;
MainMatrix[0][1]=200;
MainMatrix[1][0]=300;
MainMatrix[1][1]=400;


for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
        A[i][j]=MainMatrix[i][j];
    }
}

So, what's the difference?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

3 Answers3

3

I know that they have the same functionality

Not quite...

The second example you have two distinct objects containing the same values . Updates to one are not reflected in the other.

The first example, you have only one matrix (at least after A=MainMatrix;), and two references. Any updates to A will be reflected in MainMatrix (and vice-versa).

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thank you so much.That is exactly what I was feeling.each time I was changing a matrix I felt every matrices were changing as well.because I was using the first strategy but as I used The second strategy every thing went fine. – Mohammad Ghanatian Aug 31 '16 at 23:02
  • 1
    @MohammadGhanatian If you have found an answer to the question then please mark the answer as the "correct answer". – progyammer Sep 04 '16 at 07:09
1

In the first code snippet, A and MainMatrix both end up referring to the same array in memory. In the second snippet, you end up with two different arrays that contain the same values.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
0

The diffrence is, the first is refrencing A to MainMatrix, meaning A and MainMatrix refer to the same int[][]. if you modify MainMatrix, A is changed as well cause they point to the same location in memory.

your second way is copying MainMatrix to A, both a seperate and if you change one the other stays unchaged cause they point to diffrent locations in memory.

aldr
  • 838
  • 2
  • 19
  • 33