2.3.11 Using a Two-Dimensional Array to Represent Objects

Assign Players to a Two-Dimensional Training Schedule

The coach uses two sessions with two training stations in each session. A two-dimensional Player array can store the Player reference assigned to each session-and-station pair.

The first index identifies the session; the second identifies the station. Some positions may be unassigned and therefore contain null.

Create Assignments and Record a Turn for Each One

The established Player class has a public int field named NumberOfTurns. Place these statements inside an existing method. Jordan is deliberately assigned to two different schedule positions.

Record scheduled turns without reading through null
Player[,] assignments = new Player[2, 2];
Player jordan = new Player();
jordan.NumberOfTurns = 2;

assignments[0, 0] = jordan;
assignments[1, 1] = jordan;

int occupiedSlots = 0;

for (int session = 0; session < assignments.GetLength(0); session++)
{
    for (int station = 0; station < assignments.GetLength(1); station++)
    {
        Player current = assignments[session, station];

        if (current != null)
        {
            current.NumberOfTurns = current.NumberOfTurns + 1;

            occupiedSlots++;
        }
    }
}

The rectangular array stores references

Creating new Player[2, 2] creates four reference positions, initially null. Creating jordan is a separate operation.

The two element assignments copy Jordan's reference into [0,0] and [1,1]. They do not create two additional Players.

Check each slot before using a field

The nested loops read one slot into current. At [0,1] and [1,0], that value is null, so the if skips both body assignments.

At an occupied position, the program can reach the Player and record one turn. The index pair may be valid even when no Player occupies that position.

Trace Positions and Shared State
Session order, then station order
Pair visited Slot reference Jordan turns afterward occupiedSlots afterward
[0,0] Jordan 3 1
[0,1] null 3 1
[1,0] null 3 1
[1,1] Jordan 4 2
Inspect the Final References
After traversal, slots [0,0] and [1,1] refer to the same Jordan object with four turns. Slots [0,1] and [1,0] remain null. Two occupied slots were processed.
Two schedule slots share one Player
  • New
  • Changed
  • Removed

The picture is the state after both loops finish. The two arrows meet at one Player box, explaining why both visits affect the same field.

The null positions have no arrow to a Player. The bounds checks built into the loops protect the index pairs; the if protects the object field access.

Leave One Scheduled Position Empty