The shop keeps each customer's cart in the map carts, and its routes make new carts with makeCart: {"owner": "ana", "items": []}. The items parameter lets restoreCart bring back a saved cart. Java has no default values for parameters, so the other routes pass null, which means "no list: start empty". An AI assistant wrote it like this:
private static final List<Object> EMPTY_ITEMS = new ArrayList<>();
Map<String, Object> makeCart(String owner, List<Object> items) {
return Map.of("owner", owner, "items", items == null ? EMPTY_ITEMS : items);
}
Then Ben added a pen and found Ana's mug in his cart. Java makes the field's list once, when the class is loaded, not at each call. final only stops the field from pointing at another list; the list itself can still grow. So every cart made with null gets that same one list, and what one customer adds, every customer sees. This is a shared default. A smaller example:
static final List<String> NO_TAGS = new ArrayList<>();
static List<String> addTag(String tag, List<String> tags) {
if (tags == null) {
tags = NO_TAGS;
}
tags.add(tag);
return tags;
}
System.out.println(addTag("new", null)); // [new]
System.out.println(addTag("sale", null)); // [new, sale]: the same list again
The fix: keep null as the "no list" signal. null can't be changed, so sharing it is harmless. Then, inside the method, make a new empty ArrayList when items is null: lines inside a method run at every call, so every call gets a list of its own. A list that was passed in, like a restored cart, is kept as it is.
Your rewrite must give these answers:
POST /carts/ana/items {"product": "Mug"} → 201 {"items": ["Mug"], "owner": "ana"}
POST /carts/ben/items {"product": "Pen"} → 201 {"items": ["Pen"], "owner": "ben"}
POST /carts/ana/items {"product": "Lamp"} → 201 {"items": ["Mug", "Lamp"], "owner": "ana"}
GET /carts/ben → 200 {"items": ["Pen"], "owner": "ben"}
GET /carts/eva → 200 {"items": [], "owner": "eva"}
PUT /carts/chloe {"items": ["Plant", "Teapot"]} → 200 {"items": ["Plant", "Teapot"], "owner": "chloe"}
Your task: write makeCart so a cart made with null items gets a new empty list of its own, and a cart made with a list keeps that list.
Assignment
Follow the Coding Tutorial to write makeCart with a new list made inside the method whenever items is null.
Hint
The new list must be made inside the method, so it is made at every call. Check with items == null, and don't forget that makeCart returns the cart. When AI code keeps a list or a map in a field as a stand-in for "nothing", ask whether every call shares it.
Free plan: 30 tutor messages. PRO is unlimited.
