Retrieving and Updating Elements

You retrieve and update elements in a multi-dimensional list the same way you would for 1D lists, except now you have to deal with multiple levels of indices. The table below shows how you would retrieve each value in list. Do you see any patterns?

list

You can also think about multi-dimensional lists this way:

The first index is the first “level” of the list. The second index is the second “level” of the list. It’s list-ception!

Let’s say we’re trying to retrieve list[1][2]. How would we get there? First, look at the first level. We need to retrieve the element at index 1. That would be:

list[1][...]

Now we’re going to go a level deeper. The next index is 2, so that would be:

list[1][2]

Therefore, list[1][2] is “sheets”!

To traverse a multidimensional array, you can use a nested for loop for however many “levels” you have. For a 2D array, you’ll need 2 for loops:

for (int row = 0; row < list.length; row++) {
						for (int col = 0; col < list[row].length; col++) {
								System.out.println(list[row][col]);
						}
}