I have two classes where one class contains an ArrayList with items added to the cart and another class that prints the items from the cart. Since the ArrayList is private, I used a getter to get the products from the ArrayList and to print them in the GUI class, yet it returns nothing.
My implementation so far is,CartGUI.java
public void printCart() {
ShoppingCart shoppingCart = new ShoppingCart();
System.out.println("Products in cart: ");
for (Product p : shoppingCart.getCart()) {
System.out.println(p.getProductName());
}
}
ShoppingCart.java
private ArrayList<Product> cart = new ArrayList<>();
public ArrayList<Product> getCart() { return cart; }
I tested to see if the ArrayList was empty, but it wasn't. If the ArrayList is set as static, my code seems to work, but that's not the requirement.
I thought using a Singleton would fix this issue, but that did not work as well.
Edit: I was able to solve this by using a Singleton and passing the same instance of the ShoppingCart to the CartGUI.
In your
PrintCart()method, your ShoppingCart object is instantiated with a cart that has an empty ArrayList of products. You need to fill up that cart with a setter before you start looping through it.