Skip to Content
Course content

18: Multidimensional Arrays

Click on the "Edit" button in the top corner of the screen to edit your slide content.

When you first encounter multidimensional arrays, it's incredibly easy to visualize them as a rigid, physical grid—like a spreadsheet or a piece of graph paper. You probably imagine a perfectly rectangular block of memory where every row is guaranteed to be the same length. If you've come from a language like C or C++, this is often exactly how they work.

The "Perfect Grid" Myth

The biggest mistake I see developers make in Java is assuming that array[row][col] implies a fixed width for every row. They write code assuming that if array[0].length is 5, then every other row must also be 5. But Java doesn't actually have "true" multidimensional arrays in the way some other languages do.

// This looks like a 3x3 grid, but it's not what you think.
int[][] grid = new int[3][3];

// I can actually do this, and Java won't complain:
grid[0] = new int[2]; // Row 0 now has 2 elements
grid[1] = new int[10]; // Row 1 now has 10 elements
grid[2] = new int[1]; // Row 2 now has 1 element

If you wrote a for loop based on the assumption that the width was always 3, your program would crash with an ArrayIndexOutOfBoundsException the moment it hit the second or third row. In Java, a 2D array is simply an array of arrays. The top-level array doesn't hold data; it holds references to other arrays.

Thinking in Arrays of Arrays

To master this, you have to shift your mental model. Instead of a "table," think of a "folder containing several lists." Each list in that folder can be a different length. We call these "jagged arrays."

Let's use a real-world example: a cinema seating chart. In many theaters, the front rows are shorter than the back rows. Trying to force this into a perfect rectangle would waste memory by creating "empty" seats that don't actually exist in the building.

int[][] cinemaSeats = {
    {1, 2, 3, 4},       // Row 0: 4 seats
    {1, 2, 3, 4, 5, 6}, // Row 1: 6 seats
    {1, 2, 3, 4, 5, 6}, // Row 2: 6 seats
    {1, 2, 3, 4}        // Row 3: 4 seats
};

Because of this structure, you should almost never hard-code the inner loop limit. Instead, always reference the length of the specific row you are currently iterating over. I've spent more hours than I'd like to admit debugging production code because someone used a constant instead of .length.

Iterating Safely Through Jagged Data

The safest way to handle these is by nesting your loops and letting the array tell you how big it is at every step. Here is how I typically write a traversal for a multidimensional structure:

for (int i = 0; i < cinemaSeats.length; i++) {
    // cinemaSeats[i] is the array representing the current row
    for (int j = 0; j < cinemaSeats[i].length; j++) {
        System.out.print("Seat " + cinemaSeats[i][j] + " ");
    }
    System.out.println(); // Move to the next row
}

Notice cinemaSeats[i].length. This is the key. It doesn't matter if the first row has two seats and the second has two thousand; this code will handle both without breaking. It's a simple habit, but it's what separates a novice from a professional engineer when dealing with Java collections.




📋 Practical Task

The Jagged Warehouse Inventory Tracker

You are managing a warehouse where different aisles have a different number of shelves. You need to write a program that calculates the total number of items stored across the entire warehouse.

Requirements:

  • Create a jagged 2D array of integers named warehouseInventory.
  • The array should represent 3 aisles:
    • Aisle 0: 3 shelves with counts of 10, 15, and 20 items.
    • Aisle 1: 5 shelves with counts of 5, 5, 10, 2, and 8 items.
    • Aisle 2: 2 shelves with counts of 50 and 40 items.
  • Write a nested loop to iterate through every shelf in every aisle.
  • Calculate the sum of all items and print the final total to the console.
  • Constraint: You must use .length for both the outer and inner loops to ensure the code works regardless of how many shelves are in each aisle.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.