I have a class Order as shown below :
public class Order {
private List<OrderLine> orderLines = new ArrayList<OrderLine>();
public void add(OrderLine o) throws Exception {
if (o == null) {
System.err.println("ERROR - Order is NULL");
}
orderLines.add(o);
}
public void clear() {
this.orderLines.clear();
}
}
Now in my main I want to use one variable of order and update list and print the output
My Main class code:
public static void main(String[] args) throws Exception {
Map<String, Order> allOrders = new HashMap<String, Order>();
//Build Order 1
Order order = new Order();
order.add(new OrderLine(new Item("book", (float) 12.49), 1));
order.add(new OrderLine(new Item("Pen", (float) 14.99), 1));
allOrders.put("Order 1", order);
order.clear();
//Build Order 2
// Reuse cart for an other order
order.add(new OrderLine(new Item("imported box of chocolate", 10), 1));
order.add(new OrderLine(new Item("perfume", (float) 47.50), 1));
allOrders.put("Order 2", order);
order.clear();
}
Here I am creating one of the order object and addign details and adding this to list.Now Clearing the data in the object and updating the object with new order details but the first order details are also updated with second order details.I think Order object is Pass by reference.How to achieve object reuse avoiding pass by reference and have all order details??
Regards, Nagasree.