gpt4 book ai didi

java - 2 不同的项目添加到ArrayList,但最新的项目被创建了两次?

转载 作者:行者123 更新时间:2023-12-02 11:33:59 26 4
gpt4 key购买 nike

我有一个包含描述、产品编号和价格的产品 TableView,当用户在表中选择产品并单击按钮时,应将其添加到名为 order 的 ArrayList 中,然后将其添加到名为 order 的购物车中购物车。请参阅下面的按钮方法:

        public void addToCartButtonClicked(){
//Set the variables of the cart.
//Set customer to the cart.
shoppingCart.setShopper(newCustomer);
//Set Cart ID
shoppingCart.setCartId(cartID);

//Get selected product from the table, add to order then add to cart.
ObservableList<Product> allProducts;
allProducts = shoppingTable.getItems();
order.setProduct(shoppingTable.getSelectionModel().getSelectedItem());
shoppingCart.addOrder(order);
System.out.println(order);
}

我使用了 System.out 来尝试理解这个问题,但没有成功,因为它以前是有效的。当我添加产品“Apple”时,它会成功地将其添加到 ShoppingCart 及其属性,当我添加“Melon”时,它也会成功地将其添加到购物车,但随后会将产品“Apple”替换为“Melon”,它的属性也带有“瓜的”

这是系统打印的输出:

Cart:[contents=[Order:[item=Product:[productCode=01, description=Apple, unitPrice =99], quantity=1]]

添加第二个产品时:

Cart:[contents=[Order:[item=Product:[productCode=03, description=Melon, unitPrice =77], quantity=1], Order:[item=Product:[productCode=03, description=Melon, unitPrice =77], quantity=1]]

可能有帮助的代码:

购物车类别:

//constructors
public Cart() {
contents = new ArrayList<Order>();
shopper = new Customer();
deliveryDate = new Date();
cartId = "Not set";
}
public void addOrder(Order o) {
contents.add(o);
}

订单类别:

    //constructors
public Order() {
item = new Product();
quantity = 1;
}

产品类别:

    public Product(String productCode, String description, int unitPrice) {
this.productCode = productCode;
this.description = description;
this.unitPrice = unitPrice;
}

最佳答案

您创建了一个 Order 实例,并且在每次调用 addToCartButtonClicked() 时,您都会更改该 Order 的产品(通过调用 order.setProduct(shoppingTable.getSelectionModel().getSelectedItem())) 并将相同的 Order 添加到您的 List

因此,您的 List 包含对同一 Order 实例的多个引用。

你应该放

Order order = new Order();

在您的 addToCartButtonClicked() 方法中,以便将不同的 Order 实例添加到 List 中。

 public void addToCartButtonClicked(){
//Set the variables of the cart.
//Set customer to the cart.
shoppingCart.setShopper(newCustomer);
//Set Cart ID
shoppingCart.setCartId(cartID);

//Get selected product from the table, add to order then add to cart.
ObservableList<Product> allProducts = shoppingTable.getItems();
Order order = new Order();
order.setProduct(shoppingTable.getSelectionModel().getSelectedItem());
shoppingCart.addOrder(order);
System.out.println(order);
}

关于java - 2 不同的项目添加到ArrayList,但最新的项目被创建了两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49088338/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com