2.2.15 Arrays of Objects

Overview

An array of objects holds references at its indexed positions. Each reference can point to a different Animal object. In Zoo, the array can collect the featured animals of two zoos after both objects exist.

Animal[] animals = {
    this.ComoZoo.FeaturedAnimal,
    this.SanDiegoZoo.FeaturedAnimal
};
Animal first = animals[0];
Store Object References
Object diagram for arrays of objects: store object references.
Store Object References
  • New
  • Changed
  • Removed

The first element references Como Zoo’s featured Animal; the second references San Diego’s. Assigning first does not copy an Animal. If code changes a field through first, reading that same Animal through animals[0] sees the change.

An unfilled slot in an Animal array initially contains null. Check for null before calling a method on a slot that may not have received an object reference.

Trace the Outcome

Trace animals[0] to the Animal instance. Explain why two slots could also point to the same Animal object and how that would differ from two separate objects with matching values.