首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当相同的ID已经存在时,更新ArrayList中的元素

当相同的ID已经存在时,更新ArrayList中的元素
EN

Stack Overflow用户
提问于 2022-12-02 08:47:26
回答 1查看 35关注 0票数 0

我正在使用JSP和servlet创建一个工作购物车,用户可以在购物车中添加和删除一个项目。这些项目将显示在一个表上。除了添加具有相同ID的项时,它只是添加了一个新行,而不是更新现有的记录,这些代码对于这些特性都很好。

结果:

代码语言:javascript
运行
复制
|    Item ID    |     Item Name    |         Qty      |      Action      |
|---------------|------------------|------------------|------------------|
|       1       |        Bag       |         1        |    Remove Item   |
|       2       |     Pencil       |         5        |    Remove Item   |
|       1       |        Bag       |         3        |    Remove Item   |

预期结果:

代码语言:javascript
运行
复制
|    Item ID    |     Item Name    |         Qty      |      Action      |
|---------------|------------------|------------------|------------------|
|       1       |        Bag       |         4        |    Remove Item   |
|       2       |     Pencil       |         5        |    Remove Item   |

JSP:index.jsp

代码语言:javascript
运行
复制
<body>
        <h1>Cart</h1>
        <form action="addToCart" method="POST">
            <input type="text" name="id" placeholder="Item ID"/><br>
            <input type="text" name="itemName" placeholder="Item Name"/><br>
            <input type="text" name="qty" placeholder="Qty"/><br>
            <input type="submit" name="submit" value="Add"/><br>
        </form>
        
        <table>
            <th>Item ID</th>
            <th>Item Name</th>
            <th>Qty</th>
            <th>Action</th>
        
        <% 
            ArrayList<Item> arrayList = new ArrayList<Item>();
            if (request.getServletContext().getAttribute("cartItemList") != null) {
               arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");
               
               if(!arrayList.isEmpty()) 
               {
                    for (Item item : arrayList)
                    {
        %>
        
            <tr>
                <td><%= item.getItemId() %></td>
                <td><%= item.getItemName() %></td>
                <td><%= item.getQty() %></td>
                <td><form method="POST" action="removeFromCart">
                        <input type="text" name="id" value="<%= item.getItemId() %>" hidden/>
                        <input type="submit" name="remove" value="Remove Item">
                    </form>
                </td>
            </tr>

        <% 
                    }       
               }
            }
        %>
        </table>
    </body>l>

控制器(Servlet doPost方法):addToCart.java

代码语言:javascript
运行
复制
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        PrintWriter out = response.getWriter();
        processRequest(request, response);   
        request.getSession();
        String id = request.getParameter("id");
        String itemName = request.getParameter("itemName");
        String qty = request.getParameter("qty");

        Item item = new Item();
        item.setItemId(id);
        item.setItemName(itemName);
        item.setQty(Integer.parseInt(qty));
        
        ArrayList<Item> arrayList = new ArrayList<Item>();
        request.getSession().setAttribute("array", arrayList);
        arrayList.add(item);
        if(request.getServletContext().getAttribute("cartItemList")  != null) 
        {
            // attempt to UPDATE Quantity if the same item was previously added
            if (arrayList.contains(id)) // if arrayList already contains the same id entered by user
            {
                Iterator<Item> it = arrayList.iterator();
                //iterate through datas
                int ctr = 0;
                int total = item.getQty();
                while (it.hasNext()) 
                {
                    Item name = it.next();
                    //check if values matches
                    if (name.getItemId().equals(id)) 
                    {
                      total += name.getQty(); // add the new quantity to the existing one
                    }
                    else 
                    {
                       ctr++; 
                    }
                }
                arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");
                
                item = arrayList.get(ctr); // get the item at the index it was found
                item.setQty(total); // set the quantity to the sum of the old quantoty and new quantity entered by user
                
                //pass updated value to jsp page
                request.getSession().setAttribute("cartItemList", arrayList);
                request.getRequestDispatcher("index.jsp").forward(request, response);
                request.getSession().setAttribute("cartItemList", arrayList);
            } 
            else if (!arrayList.contains(id)) // if arrayList does not contain the same id entered by user
            {
                arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");
                arrayList.add(item);
                request.getServletContext().setAttribute("cartItemList", arrayList);
            }
        }
        else
        {
            request.getServletContext().setAttribute("cartItemList", arrayList); 
        } 
        
        response.sendRedirect("index.jsp");
    }

模型:Item.java

代码语言:javascript
运行
复制
public class Item {
    private String itemId;
    private String itemName;
    private int qty;
    private String submit;

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }
}

我在addToCart.java中标记了我试图创建代码的部分,以便用它的新数量更新特定的行。我只是不知道我应该放置什么代码,以便更新现有的数量,而不是创建一个新的行。提前感谢您的帮助!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-12-02 09:24:32

由于对象的原因,arrayList.contains(id)永远不会是相同的。必须在Item类中实现equalshashcode

代码语言:javascript
运行
复制
public class Item {
    private String itemId;
    private String itemName;
    private int qty;
    private String submit;

    public String getItemId() {
        return itemId;
    }

    public void setItemId(String itemId) {
        this.itemId = itemId;
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    @Override
    public int hashCode() {
        return Objects.hash(itemId);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Item)) {
            return false;
        }
        Item other = (Item) obj;
        return Objects.equals(itemId, other.itemId);
    }

}

上面的代码通过检查itemId是否相同,然后考虑该对象相同,尽管qty是不同的。

还有。查找现有项目和更新的逻辑似乎是错误的。如果项目匹配,则需要中断for循环。更新addToCart.java中的代码。

代码语言:javascript
运行
复制
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    processRequest(request, response);
    request.getSession();
    String id = request.getParameter("id");
    String itemName = request.getParameter("itemName");
    String qty = request.getParameter("qty");

    Item item = new Item();
    item.setItemId(id);
    item.setItemName(itemName);
    item.setQty(Integer.parseInt(qty));

    ArrayList<Item> arrayList = new ArrayList<>();
    if (request.getServletContext().getAttribute("cartItemList") != null) {
        arrayList = (ArrayList<Item>) request.getServletContext().getAttribute("cartItemList");
        // attempt to UPDATE Quantity if the same item was previously added
        if (arrayList.contains(item)) {
            Item existingItem = arrayList.get(arrayList.indexOf(item));
            existingItem.setQty(existingItem.getQty() + item.getQty());
            // pass updated value to jsp page
            request.getSession().setAttribute("cartItemList", arrayList);
            request.getRequestDispatcher("index.jsp").forward(request, response);
            request.getSession().setAttribute("cartItemList", arrayList);
        } else {
            arrayList.add(item);
            request.getServletContext().setAttribute("cartItemList", arrayList);
        }
    } else {
        arrayList.add(item);
        request.getServletContext().setAttribute("cartItemList", arrayList);
    }
    response.sendRedirect("index.jsp");
}

更多细节https://initialcommit.com/blog/working-hashcode-equals-java

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74653010

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档