2个不同的项添加到ArrayList但最新的项目是两次?

时间:2018-03-03 19:30:37

标签: java arraylist javafx observablelist

我有一个产品的TableView,它有描述,产品编号和价格,当用户在表格中选择产品并点击按钮时,它应该被添加到一个名为orderList的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;
}

1 个答案:

答案 0 :(得分:1)

您创建了一个Order个实例,并在每次调用addToCartButtonClicked()时更改了Order的产品(通过调用order.setProduct(shoppingTable.getSelectionModel().getSelectedItem()))并添加相同的Order List 1}}到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); } 个实例。

console.log('test')
相关问题