Java Design Program · CD01
Create an Immutable Class in Java
An immutable object never changes after it is built. To "change" it, you create a new object, which makes it safe to share between threads and to use as a map key.
Problem Statement
Write an Invoice class with an id, an amount and a list of items whose state can never change after construction, not even through the list passed in or the list returned.
Provide withAmount(), which returns a new invoice with a different amount and leaves the original untouched.
Input/Output Examples
new Invoice("INV-7", 500, [keyboard, mouse]); then add "monitor" to the source listOutputitems stay [keyboard, mouse]Explanation: the constructor copied the list.original.withAmount(700)Outputa new invoice with amount 700Explanation: the original still has amount 500.original.items().add("cable")OutputUnsupportedOperationExceptionExplanation: the stored list is unmodifiable.Visual Explanation
- ConstructoritemskeyboardmouseList.copyOf(items) copy in
- Caller addssource listkeyboardmousemonitoroutside list changes invoice unaffected
- withAmount(700)objects500700new object, same items
- Doneoriginal unchanged
withAmount() returns a new object instead of changing the old one.An object is only immutable if nothing outside it can reach its mutable parts. Copying mutable inputs and returning unmodifiable views closes both doors.
Approaches
Both approaches produce the same immutable invoice. The first spells out every rule; the second lets a record do most of the work.
Approach 1: Final Class With Defensive Copies (Recommended)
Idea: make the class final, every field private final, provide no setters, and copy mutable inputs with List.copyOf().
- Declare the class
finalso no subclass can add mutable state. - Make every field
private finaland set it only in the constructor. - Copy the list in the constructor with
List.copyOf(), which also makes it unmodifiable. - Return new objects from with-methods instead of changing fields.
Time: O(k) · Space: O(k). Construction copies the k items once.
Approach 2: Record With a Compact Constructor
Idea: a record already has private final fields, accessors, equals() and hashCode(); the compact constructor adds the defensive copy.
- Declare
record Invoice(String id, BigDecimal amount, List<String> items). - In the compact constructor, reassign
items = List.copyOf(items). - Add a
withAmount()method that returns a new record.
Time: O(k) · Space: O(k).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Final Class With Defensive Copies (Recommended)
This is the classic checklist answer, and it works on every Java version that has List.copyOf() (Java 10+).
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class ImmutableFinalClass {
// final class, private final fields, no setters, defensive copies of mutable data
static final class Invoice {
private final String id;
private final BigDecimal amount;
private final List<String> items;
Invoice(String id, BigDecimal amount, List<String> items) {
this.id = id;
this.amount = amount;
this.items = List.copyOf(items); // copy in: later changes to the caller's list do not leak in
}
String id() { return id; }
BigDecimal amount() { return amount; }
List<String> items() { return items; } // already unmodifiable, safe to return
Invoice withAmount(BigDecimal newAmount) {
return new Invoice(id, newAmount, items); // "changing" means creating a new object
}
@Override
public String toString() {
return "Invoice[id=" + id + ", amount=" + amount + ", items=" + items + "]";
}
}
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("keyboard", "mouse"));
Invoice original = new Invoice("INV-7", new BigDecimal("500"), source);
source.add("monitor"); // try to change it from outside
Invoice updated = original.withAmount(new BigDecimal("700"));
System.out.println("original: " + original);
System.out.println("updated: " + updated);
try {
original.items().add("cable");
} catch (UnsupportedOperationException e) {
System.out.println("items().add() -> UnsupportedOperationException");
}
}
}
original: Invoice[id=INV-7, amount=500, items=[keyboard, mouse]] updated: Invoice[id=INV-7, amount=700, items=[keyboard, mouse]] items().add() -> UnsupportedOperationException
Time complexity: O(k) · Space complexity: O(k).
Approach 2: Record With a Compact Constructor
Records (Java 16+) are shallowly immutable; the compact constructor is what makes the list field safe too.
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class ImmutableRecord {
// A record's fields are private and final; the compact constructor adds the defensive copy
record Invoice(String id, BigDecimal amount, List<String> items) {
Invoice {
items = List.copyOf(items);
}
Invoice withAmount(BigDecimal newAmount) {
return new Invoice(id, newAmount, items);
}
}
public static void main(String[] args) {
List<String> source = new ArrayList<>(List.of("keyboard", "mouse"));
Invoice original = new Invoice("INV-7", new BigDecimal("500"), source);
source.add("monitor");
Invoice updated = original.withAmount(new BigDecimal("700"));
System.out.println("original: " + original);
System.out.println("updated: " + updated);
try {
original.items().add("cable");
} catch (UnsupportedOperationException e) {
System.out.println("items().add() -> UnsupportedOperationException");
}
}
}
original: Invoice[id=INV-7, amount=500, items=[keyboard, mouse]] updated: Invoice[id=INV-7, amount=700, items=[keyboard, mouse]] items().add() -> UnsupportedOperationException
Time complexity: O(k) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Final Class With Defensive Copies | O(k) | O(k) |
| Record With a Compact Constructor | O(k) | O(k) |
Here k is the number of items. Creating an invoice copies the list once; reading it never copies anything because the stored list is already unmodifiable.
Interview Tips and Recommended Approach
- Recite the rules: final class, private final fields, no setters, defensive copies in and out.
- Remember mutable fields.
final Listonly fixes the reference; the list itself can still change. - Know that records are shallowly immutable. A record holding a mutable list still needs a copy.
- Explain the benefits: thread safety without locks, safe map keys and simpler reasoning.
Recommended Approach: Final Class With Defensive Copies
Why: it shows every rule explicitly, which is what interviewers want to hear. In new code, a record with a compact constructor is the shorter way to get the same result.