Some Mysteries of objectdraw, ExplainedTopRagged Two-Dimensional Arrays

Ragged Two-Dimensional Arrays

As mentioned earlier, we can create two-dimensional arrays where each row has a different length. Calendars (see details in book) provide a good example. Each row of the array will represent a month. We can declare it as:

    private String[][] dailyEvent;

We can create 12 months by creating just slots for each month:

   dailyEvent = new String[12][];

Because we have not filled in the other dimension (size of the rows), we will have to create each month separately. If somewhere else we wrote a method getDays(int n) that returns the number of days in month n (where 1 represents January), then we can create all of the months as follows:

    for (int month = 0; month < 12; month++)
       dailyEvent[month] = new String[getDays(month+1)];
    }

Why do we need to write month+1 in the call to getDays?


Some Mysteries of objectdraw, ExplainedTopRagged Two-Dimensional Arrays