Java
Updating quantity
Manage cart with updateQuantity and removeItem.
Updating quantity
In this lesson we'll learn to update and remove an item in the cart. cart.set(i, newValue) replaces the i-th item; cart.remove(i) deletes it:
cart.set(0, "Apple x2"); // replaces first item
cart.remove(1); // deletes second item
Indexes start at 0. set changes the item but keeps the size; remove deletes the item and shrinks the size by one. After removal, indexes shift; so pay attention to the removal order.
Index and ordering
set and remove take an index. Indexes start at 0: cart.get(0) is the first, cart.get(1) the second item.
ArrayList<String> cart = new ArrayList<>();
cart.add("Apple");
cart.add("Bread");
cart.set(0, "Apple x2"); // [Apple x2, Bread]
cart.remove(1); // [Apple x2]
Use set(0, ...) to replace the first item, remove(1) to delete the second. After removal, the remaining items' indexes shift.
Exercise Update and remove items
Add to the previous code: update the first item with cart.set(0, "Apple x2"), delete the second with cart.remove(1). Print the updated cart with System.out.println(cart). (Keep the price and total lines.)
Show example solution
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> cart = new ArrayList<>();
cart.add("Apple");
cart.add("Bread");
cart.set(0, "Apple x2");
cart.remove(1);
ArrayList<Double> prices = new ArrayList<>();
prices.add(10.0);
prices.add(20.0);
double subtotal = 0;
for (double price : prices) {
subtotal += price;
}
double tax = subtotal * 0.10;
double total = subtotal + tax;
System.out.println(cart);
System.out.println("Subtotal: " + subtotal);
System.out.println("Total: " + total);
}
}
Test yourself
-
Match the update methods
- set
- Replace item
- remove
- Delete item
- add
- Add item
- size()
- Item count
-
What does cart.set(0, "Apple x2") do?
- Adds Apple x2 to the cart
- Removes Apple x2 from the cart
- Sorts the cart
- Makes the first item Apple x2
Show answer
Makes the first item Apple x2 — set(0, ...) replaces the first item.
-
Complete the remove call
cart.____(1);
Show answer
cart.remove(1);
Next lesson: Putting it together