Copying arrays in Java

I recently started learning how to develop Android apps. I’m working on a game at the moment, and I had been tearing my hair out over what I thought was the most elusive bug ever.

Basically, I have two integer arrays: currentLocations and initialLocations. They hold the “room numbers” of various game objects/NPCs within the game. At the start of the first game, both arrays are populated with random values:

public class GameClass extends Activity {
	private static int[] currentLocations = new int[6];
	private static int[] initialLocations = new int[6];

	...

	private void setupLocations {
		for (int i=0; i<7; i++) {
			currentLocations[i] = getRandomLocation();
			initialLocations[i] = currentLocations[i];
		}
	}
}

Then, throughout the game, currentLocations is changed (most notably, the player’s location changes). After the first game ends, the player is asked whether the locations should be mixed up. In the case that the player wants to keep the initial locations, this function is called:

private void restoreInitialLocations() {
	currentLocations = initialLocations;
}

However, in my testing, every time the game ended and the initial locations were “restored”, it seemed like the player would start a new game in the same place he left off.

The only place I made changes to initialLocations was in setupLocations(), so I was quite perplexed. I eventually thought to display the values of initialLocations in the game in real-time to track what was happening. After I did, I noticed it was quite literally holding the same values as currentLocations.

After a few minutes of thinking about it, I realized that the statement in restoreInitialLocations() was the culprit. I don’t know why it makes initialLocations into a pointer of sorts to currentLocations, but I now faintly remember, from way back when I was first learning Java, that the proper way to copy the values of one array into another is:

for (int i=0; i<7; i++) {
	currentLocations[i] = initialLocations[i];
}

That’s a lesson I hope I won’t have to learn again anytime soon!

This entry was posted in Programming and tagged , , , , . Bookmark the permalink. Both comments and trackbacks are currently closed.
  • Recent Posts

  • Topics

  • Archives