Part 6 of 6 · 2 min read
Exercises
Easy
Easy 1: Predict the sharing (20 minutes)
Write what you expect from a shallow copy and a deep copy when the copy's first attendee is renamed. Then run the example.
Done when: your prediction and the real output ("ravi", then "asha") are written together.
Hint
The two copies differ only in how the list is made.
Easy 2: Run the registry (20 minutes)
Type the registry code and create a meeting from "standup", then change its title.
Done when: the copy prints "Standup (Friday)" and the stored one prints "Standup".
Hint
create copies before returning.
Easy 3: Mutable or not (20 minutes)
List the fields of MeetingTemplate and mark each as immutable (safe to share) or mutable (must be copied).
Done when: you have a table with a reason for every field.
Hint
A String cannot be changed after creation.
Medium
Medium 1: Document template (45 minutes)
Write a Document with a title and a list of Section objects. Add a copy constructor and prove the copy is independent.
Done when: a test changes a section text in the copy and the original is unchanged.
Hint
Copy each Section and not only the list.
Medium 2: Conversion constructor (45 minutes)
Write Roster(Collection<String> names) that copies any collection into a sorted list. Test it with a HashSet and a LinkedList.
Done when: both inputs give the same sorted roster.
Hint
new ArrayList<>(names) then Collections.sort.
Medium 3: Break clone (45 minutes)
Write a class with a List field that uses super.clone() and show that the copy shares the list. Then fix it with a copy constructor.
Done when: you show the bug and the fix with output.
Hint
super.clone() copies the reference, not the list.
Hard
Hard 1: Prototype of a tree (90 minutes)
Make a Folder that holds files and other folders. Write a deep copy that handles any depth.
Done when: a copy of a three-level tree can be edited without changing the original.
Hint
Use recursion in the copy constructor.
Hard 2: Registry with variations (90 minutes)
Build a registry of enemy types for a game with health and speed values. Make new types by copying and changing values, with no new subclasses.
Done when: five enemy types exist and only one class defines them.
Hint
One Enemy class and a map of templates.
Hard 3: Choose the creator (90 minutes)
For three cases (parking tickets, theme palettes, report templates), decide between a factory, a builder and a prototype. Defend each choice in two sentences.
Done when: three decisions are written with a reason and the cost of the choice.
Hint
Prototypes fit few combinations that need a small edit.