2015-07-03 126 views
0

如果我有产品清单(清单):的Java:从一个ArrayList中transfering元素到另一个的ArrayList

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

后客户选择某一特定产品的报价,我可以/我怎么去除来自productList(我的库存)的产品,并将其放在另一个列表(客户的购物车)中?从这里,如果顾客决定他/她不想购买产品(继续结帐),我可以/如何从购物车中删除此产品。&返回到productList?

+1

你看过Java文档中的List API吗?你有什么尝试? –

回答

2

您可以使用List.remove(Product)List.add(Product)方法。

只要确保Product类中的equals方法正确实施,并且因为remove()方法将元素从列表中移除,如果equals方法返回true。

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

客户选择的产品

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

检查,如果客户签出

boolean customerChecksOut = true; 

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

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

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

您还需要重载equals & hashCode方法在你的产品类别。

相关问题