0

If I have a list of Products(an inventory):

public List<Product> productList = new ArrayList<>();

After a customer selects a given product for purchase, can I/how do I remove the product from productList(my inventory) and place it in another list (the customer's shoppingCart)? From here, if the customer decides he/she would not like to purchase the product (proceed to checkout) can I/how do I remove this product from shoppingCart & return it to productList?

1
  • 1
    Have you looked at the List API in the Java Docs? What have you tried? Commented Jul 3, 2015 at 17:04

2 Answers 2

2

You can use List.remove(Product) and List.add(Product) methods.

Just make sure that the equals method in Product class is implemented properly and because the remove() method removes the element from list if equals method returns true.

Sign up to request clarification or add additional context in comments.

Comments

1
public List<Product> productList = new ArrayList<>();
public List<Product> shoppingCart = new ArrayList<Product>();

Customer selects the product

shoppingCart.add(p); //p is the product object

Check if the customer checks out

 boolean customerChecksOut = true;

 if(customerChecksOut)
 customerChecksOut(p);
 else
 customerDropsTheProduct(p);

 void customerChecksOut(Product p){
 productList.remove(p);
 }

 void customerDropsTheProduct(p)
 {
 shoppingCart.remove(p);
 }

You also need to override the equals & hashcode method in your product class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.