LearnFrenzy
Sign in Take a free test

Object Class and Wrapper Classes · Object and Wrapper Programs · Question 5

Deep copy of an order with a copy constructor in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links