Java · Coding problem

An Immutable Basket

A free coding problem from the Java: Objects, Equality, Immutability skill. Read it here, then solve it in the app in Java.

  • Easy
  • Coding problem
  • Free
  • Java

The problem

A grocery app in Denver passes a customer's Basket between several services, so the basket must never change after it's created. It's a record:

record Basket(List<String> items) { ... }

Write its compact constructor so that:

  • The basket keeps its own copy of the items. If the caller changes the list they passed in afterwards, the basket doesn't change.
  • items() can't be used to change the basket: adding to it throws UnsupportedOperationException.
  • A basket with no items, or with a blank item (empty or only spaces), is rejected with an IllegalArgumentException.

The record already gives you equals, hashCode and toString: two baskets with the same items are equal.

The driver builds a basket, changes its own list, tries to add through items(), compares two baskets, and then tries three invalid baskets. Run the sample to see the exact output.

Constraints

  • 1 <= number of items <= 100
  • each item is one word

How it's graded

  • Run checks your code against the examples. Submit also runs hidden tests, and you see pass or fail for them, never their inputs.
  • Stuck? Hints come in four steps, from a nudge to a code skeleton, each costing part of the points.
  • Once you pass, you see the approaches from brute force to optimal, and where your solution lands among them.

More problems in Java: Objects, Equality, Immutability

Solve it An Immutable Basket free

No card needed. Lessons, practice questions and easy problems are free forever.

Free plan, no card · 7-day Pro trial · Cancel anytime