I need to create a simple cart that gets data from an url and stores it in a List and then to a session. If an item is not in the cart it is added to the List. If it is already in the cart, I increment the value by one.
This is my code so far, but it doesn't add any item to the cart.
String pid = request.getParameter("id");
String price = request.getParameter("price");
HttpSession s = request.getSession();
ArrayList<CartItem> cart = (ArrayList<CartItem>) s.getAttribute("cart");
if(cart == null){
cart = new ArrayList<>();
}
for (CartItem item : cart) {
if (item.getId().equals(pid)) {
int count = item.getCount();
item.setCount(count + 1);
} else {
cart.add(new CartItem(pid, 1, price));
}
}
s.setAttribute("cart", cart);
for (CartItem item : cart) {, how many times do you expect that loop to run? Why? (Hint: what is incartbefore the loop runs?)