Detect shared mutable composition parts

A navigation application implements the composition shown in this UML excerpt. A waypoint's x coordinate is measured in metres.


A composition connects RoutePlan to one or more Waypoint parts, with each Waypoint belonging to at most one RoutePlan.


An additional implementation requirement says that each plan must store independent waypoint copies: callers must not be able to change stored coordinates through either the supplied data or returned data. This copying requirement is explicit; do not infer it from the composition diamond alone.


Review this candidate implementation. Assume every supplied array is non-null, nonempty, and contains only non-null waypoints.


Java
class Waypoint {
    int x;

    Waypoint(int x) {
        this.x = x;
    }
}

class RoutePlan {
    private Waypoint[] waypoints;

    RoutePlan(Waypoint[] input) {
        waypoints = input.clone();
    }

    Waypoint[] copyWaypoints() {
        return waypoints.clone();
    }
}


A test method in the same package executes these statements in order:


Java
Waypoint original = new Waypoint(5);
Waypoint[] supplied = { original };
RoutePlan plan = new RoutePlan(supplied);
original.x = 9;
Waypoint[] returned = plan.copyWaypoints();
returned[0].x = 12;
returned[0] = new Waypoint(25);


Complete the table for the state immediately after the last statement. Rows labelled stored refer to plan's private array, inspected with a debugger. Enter exact integers; coordinate rows use metres.

QuantityValue
Stored array length
Stored first waypoint x (m)
Original waypoint x (m)
Returned first waypoint x (m)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Implementing Class Diagrams in Java Questions: