Java variable is changing without assignment

Joseph Gioia :

I don't understand why the variable initialCoordinates is changing. When I run the program, initialCoordinates changes values after each run of the loop.

int[] initialCoordinates = { 26, 0 };
int[] positions = { 1, 2, 3, 4 };
int[][] coordinates = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
for (int i = 0; i < 4; i++) {
    System.out.println("Initial: " + initialCoordinates[1]);
    coordinates[i] = initialCoordinates;
    coordinates[i][1] += positions[i];
}
Mark :

In your example you're setting coordinates[i] to initialCoordinates.

Then in the next line you're executing coordinates[i][1] = ..., that's when you're accesing initialCoordinates indirectly through coordinates[i] and changing the the value of initialCoordinates[1].

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84488&siteId=1