[英]How to copy only distinct elements from one arrayList to another ArrayList
[英]Java: transfering elements from one ArrayList to another ArrayList
如果我有产品列表(库存):
public List<Product> productList = new ArrayList<>();
客户选择要购买的给定产品后,是否可以/如何从productList(我的库存)中删除该产品并将其放置在另一个列表中(客户的购物车)? 从这里开始,如果客户确定他/她不想购买该产品(进行结帐),我/我如何从ShoppingCart中删除该产品并将其返回到productList?
您可以使用List.remove(Product)
和List.add(Product)
方法。
只要确保Product
类中的equals
方法已正确实现,并且因为equals方法返回true时, remove()
方法将从列表中删除该元素。
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方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.