0

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);
1
  • In your own words, where the code says for (CartItem item : cart) {, how many times do you expect that loop to run? Why? (Hint: what is in cart before the loop runs?) Commented Jun 22, 2022 at 8:10

2 Answers 2

5

Your code only adds an item if the current item being checked does not match their ids. If there are no items in the cart, the loop doesn't run and nothing gets added.

You could use a flag found to see if the loop found anything, and if not, do the add:

boolean found = false;
for (CartItem item : cart) {
    if (item.getId().equals(pid)) {
        int count = item.getCount();
        item.setCount(count + 1);
        found = true;
        break;
    }
}
if (!found) {
    cart.add(new CartItem(pid, 1, price));
}

Alternatively, you could use a HashMap (or LinkedHashMap if the order matters) and thus no looping is required:

Map<String, CartItem> cart = (Map<String, CartItem>) s.getAttribute("cart");

if(cart == null){
    cart = new LinkedHashMap<>();
    s.setAttribute("cart", cart);
}

CartItem item = cart.computeIfAbsent(pid, k -> new CartItem(k, 0, price));
item.setCount(item.getCount() + 1);
Sign up to request clarification or add additional context in comments.

2 Comments

There has got to be a canonical duplicate for the elementary technique of searching by iteration, setting a flag, and checking it after the loop.
Thank you! Now it does exactly what I want.
0

Check if ArrayList<CartItem> cart = (ArrayList<CartItem>) s.getAttribute("cart"); is returning a non-empty List. If it return an non-empty List , your for each iterator will throw java.util.ConcurrentModificationException , so handle that. Also if the List is empty just add the cartitem into the List or else no items will ever be added, since For-Each body will ever be executed unless it's non-empty.

    if(!Objects.isNull(cart) && cart.isEmpty()) {
        cart.add(new CartItem(pid, 1, price));
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.