2.2.15 Arrays of Objects

Store Player References in an Array

An array of a class type stores object references. Creating a Player array creates its element positions; it does not create a Player for every position. Each Player must be created separately and then assigned to a slot.

Explore the Soccer Example

The Player type already has a public int field named NumberOfTurns. Place these statements inside an existing method.

Store Player References in an Array
Player[] players = new Player[3];
players[0] = new Player();
players[0].NumberOfTurns = 2;

players[1] = players[0];
Understand the Code

Begin with three null slots

new Player[3] allocates three positions for Player references. All three initially contain null. Length is 3 even though none of the positions initially reaches a Player.

Create a Player before reading its fields

players[0] = new Player(); creates one Player and stores its reference in index 0. The following field assignment can now reach that Player and set NumberOfTurns to 2.

Copying a reference shares the object

players[1] = players[0]; copies the reference from index 0 into index 1. Both positions now reach the same Player. No second Player was created.

A field change through either position would affect that one shared object.

An unused slot can cause a null-reference error

Index 2 is a valid position, but it still contains null. Reading players[2].NumberOfTurns would throw NullReferenceException.

The position exists; the Player through that position does not. Check the slot for null before using a Player field.

Follow each arrow to the object that owns the field

The NumberOfTurns field belongs to the Player object, not independently to each array slot. Because both arrows reach one Player, either slot provides a path to that same field.

Replacing a slot reference would be different from changing the field through it. A replacement redirects that one slot; a field update changes the object reached by every alias.

Check the Values
Worked soccer example
Index Reference after the code NumberOfTurns access
0 The created Player Reads 2
1 The same Player Reads 2
2 null Field access would fail
Try a Small Change
Predict the Result
Use the Original Diagram to Check Your Reasoning

The diagram below shows the original example. Compare it with your prediction for the requested change; its pictured values have not been replaced by the practice inputs.

Store Player References in an Array.
Store Player References in an Array
  • New
  • Changed
  • Removed

Two labeled arrows leave the array and reach the same Player box. They represent the references in indexes 0 and 1. The row at index 2 contains null, so it has no arrow to a Player.