Write Order and LineItem classes with copy constructors that deep-copy an order (including its list of items); modify the copy and show that the original is unchanged. Also override toString.
Solution
Main.java
import java.util.ArrayList;
import java.util.List;
class LineItem {
String product;
int qty;
LineItem(String p, int q) { product = p; qty = q; }
LineItem(LineItem o) { this(o.product, o.qty); }
@Override public String toString() { return product + "x" + qty; }
}
class Order {
final String id;
final List<LineItem> items = new ArrayList<>();
Order(String id) { this.id = id; }
Order(Order o, String newId) { // deep copy
this(newId);
for (LineItem li : o.items) items.add(new LineItem(li));
}
@Override public String toString() { return id + items; }
}
public class Main {
public static void main(String[] args) {
Order original = new Order("ORD-1");
original.items.add(new LineItem("pen", 2));
original.items.add(new LineItem("book", 1));
Order reorder = new Order(original, "ORD-2");
reorder.items.get(0).qty = 10;
reorder.items.add(new LineItem("bag", 1));
System.out.println(original);
System.out.println(reorder);
}
}
Output Verified by compiling and running
ORD-1[penx2, bookx1]
ORD-2[penx10, bookx1, bagx1]
Copying the list and each LineItem makes the two orders fully independent – without clone() and its pitfalls.
More Object Class and Wrapper Classes practice questions
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!