Copy the list, then change its contents

An inventory application executes the Java fragment below. The ArrayList constructor used for review creates a separate list containing the element references from cart. Find the final sum of units across cart and the final sum across review. Report both totals in units as exact integers.


Java
class Item {
    int units;
    Item(int units) {
        this.units = units;
    }
}

var cart = new java.util.ArrayList<>(
    java.util.List.of(new Item(12), new Item(7))
);
var review = new java.util.ArrayList<>(cart);
cart.get(0).units -= 5;
review.set(1, new Item(4));
Your answers

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 Arrays of Objects Questions: