2.2.14 Replacing Values in an Array

Overview

Assigning to an indexed position replaces the value stored there. The array object and its length stay the same. An airline application can change one seat number without constructing a new array.

int[] seats = { 12, 14, 16 };
seats[1] = 15;
Update One Existing Element
Object diagram for replacing values in an array: update one existing element.
Update One Existing Element
  • New
  • Changed
  • Removed

After the assignment, the values are 12, 15, 16. Index 1 identifies the position that changed; the number 14 is overwritten. Other elements remain unchanged. The index must still be valid or the assignment fails.

A class with an array field continues to reference the same array after one element changes. Replacing a value at an index is different from assigning a whole new array to the field.

Trace the Outcome

Sketch the array before and after the assignment. Name the unchanged indexes and the replaced value. Then predict the result of seats[1].