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?
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.