【问题标题】:function returns an ArrayList empty of data函数返回一个空数据的 ArrayList
【发布时间】:2020-12-14 20:18:55
【问题描述】:

当用户单击 javaFx 中的按钮时,尝试将类的对象添加到对象的 ArralyList。我正在尝试将类(产品)的对象添加到 ArrayList shoppingList,它是产品的 ArrayList。当我在 addToCart() 函数中测试 ArrayList 时,一切都很好,但是当程序返回 main 时,ArrayList 是空的数据

这是我调用函数的主要地方

ArrayList<Product> shoppingList = new ArrayList<>();
    Button btnAddToCart = new Button("Add to cart");

  btnAddToCart.setOnAction(e->addToCart(productList,productBox,shoppingList));

这里是函数

 public ArrayList<Product> addToCart(ArrayList<Product> productList, ChoiceBox productBox, ArrayList<Product> shoppingList) {



    for(int x =0 ; x<productList.size();x++)
    {
        if(productList.get(x).getProductDescribtion() == productBox.getValue())
        {
            Product inCartProduct = new Product(productList.get(x).getProductCategory(),productList.get(x).getProductDescribtion(),
                    productList.get(x).getItemNumber(),productList.get(x).getInStockQty(),productList.get(x).getProductPrice() );

            System.out.println("Cart in for loop :>"+inCartProduct.toString());

            shoppingList.add(inCartProduct);


        }
    }
    for(Product onePr : shoppingList)
    {
       // System.out.println("Here in the cart : ");
        System.out.println("Cart in button function :> "+onePr.toString());
      //  System.out.println("The size of the cart : "+shoppingList.size());
    }


    return  shoppingList;
}

【问题讨论】:

  • 首先:重构第一个 for 以使用附魔 for 循环。第二:向Product 添加一个复制构造函数,它以另一个Product 作为唯一参数并从中初始化它的状态。
  • 你能告诉我怎么做吗

标签: java javafx-8


【解决方案1】:

对于比较值,请使用 .equals(...) 而不是 ==

if(productList.get(x).getProductDescribtion().equals(productBox.getValue()))

...而不是

if(productList.get(x).getProductDescribtion() == productBox.getValue())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 2019-04-23
    • 2019-10-31
    • 1970-01-01
    相关资源
    最近更新 更多