Home > Back-end >  Adding a new item to ArrayList doesn't work
Adding a new item to ArrayList doesn't work

Time:06-22

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);

CodePudding user response:

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);

CodePudding user response:

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));
    }
  • Related