OK let’s say I have this array:
public int[][] loadBoard(int map) {
if (map == 1) { return new int[][] {
{2,2,24,24,24,24,24,1,3,0,0,0,1 }, {
2,2,24,23,23,23,24,1,3,0,0,0,1 }, {
1,1,24,23,23,23,24,1,3,3,3,3,1 }, {
1,1,24,24,23,24,24,1,1,1,1,3,1 }, {
1,1,1,1,7,1,1,1,1,1,1,3,1 }, {
6,1,1,1,7,7,7,7,7,1,1,1,1 }, {
6,3,3,1,3,3,3,1,7,7,7,3,1 }, {
6,72,3,3,3,1,1,1,1,7,7,1,1 }, {
3,3,3,3,1,1,1,1,1,1,7,1,1 } }; } }
return board;
and I can call it doing this:
board = loadBoard(1);
But… let’s say I want to change the number 72 on map 1 array (bottom-left in the array) to the number… 21. Can you do that?
Explanation: When dealing with an array
a[],a[n]references the (n+1)th element (keeping in mind the first element isa[0].A multidimensional array is just an array of arrays. So if you have a 2D array
b[][], thenb[n]references the (n+1)th array.Your value 72 is in the 8th array (index 7), at the 2nd position (index 1). Therefore
board[7][1]references that value, andboard[7][1] = 21assigns it the value 21.Aside: Sometimes (usually, even) you don’t know when you write the code which indexes you want to work with, (say you want to do it generically for all maps). This code will find all occurrences of
72and replace them with21: