【问题标题】:How can I remove a specific object from an arrayList and how can I check if it contains this object?如何从 arrayList 中删除特定对象以及如何检查它是否包含该对象?
【发布时间】:2016-04-25 00:22:15
【问题描述】:

我有一个 arrayList 类型的购物车。当我在购物车中添加新商品时,我会先检查购物车是否已经有该商品。但是 cart.contains(item) 方法不起作用,即使购物车中有相同的商品,它也会返回 false。 第二个问题是我无法从购物车数组列表中删除这个项目对象。我的代码如下所示:

@Controller
@RequestMapping("/addTo.htm")
public class AddToController{
    @SuppressWarnings("unchecked")
    @RequestMapping(method=RequestMethod.GET)
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        System.out.println(action);
        ModelAndView mv = new ModelAndView();
        ArrayList<Item> cart;
        if(session.getAttribute("cart") != null) {
            cart = (ArrayList<Item>) session.getAttribute("cart");
        }else {
            cart = new ArrayList<Item>();
        }
        if(action.equals("addToCart")) {
            long itemId = Long.parseLong(request.getParameter("itemId"));
            ItemDAO itemDao = new ItemDAO();
            Item item = itemDao.get(itemId);
            System.out.println("111"+cart.contains(item));
            if (!cart.contains(item)) {
                cart.add(item);
            }
            double total = 0;
            int count = 0;
            for (Item i : cart) {
                total = total + i.getPrice();
                count += 1;
            }
            session.setAttribute("cart", cart);
            mv.addObject("total", total);
            mv.addObject("count", count);
            mv.setViewName("User/viewCart");
        }
        if(action.equals("remove")){
            System.out.println("cart size is" + cart.size());
            Long itemId = Long.parseLong(request.getParameter("item"));
            ItemDAO itemDao= new ItemDAO();
            Item item = itemDao.get(itemId);
            System.out.println(cart.contains(item));
            session.setAttribute("cart", cart);
            System.out.println(cart.size());
        }
        return mv;
    }
}

谁能帮我解决这个问题?谢谢!!

【问题讨论】:

    标签: java spring arraylist controller


    【解决方案1】:

    您需要向 Item 类添加一个.equals 方法,以便 ArrayLists 知道如何比较两个不同的对象。当我们这样做时,我们还应该添加一个hashCode 方法。这主要对 Set 有用,但在需要时将其作为备份总是好的。

    我们可以使用 .indexOf(Item) 方法来获取对象在列表中的位置。如果数字返回如果-1。然后它不在列表中。如果它是 0 或更大,那么它就在那里,我们可以使用索引来删除该项目。

    public class Item{
      private String type;
    
      public Item(String type){
        this.type = type;
      }
    
      public String getType(){
        return type;
      }
    
      @Override
      public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((type == null) ? 0 : type.hashCode());
        return result;
      }
    
      @Override
      public boolean equals(Object obj) {
        if (this == obj)
          return true;
        if (obj == null)
          return false;
        if (!(obj instanceof Item))
          return false;
        Item other = (Item) obj;
        if (type == null) {
          if (other.type != null)
            return false;
        } else if (!type.equals(other.type))
          return false;
        return true;
      }
    }
    

    现在我们有了一个 .equals 和哈希码。我们现在可以在 ArrayList 中比较它们。

    ArrayList<Item> itemList = new ArrayList<Item>();
    
    // Fill the list
    itemList.add(new Item("Banana"));
    itemList.add(new Item("Toaster"));
    itemList.add(new Item("Screw Driver"));
    
    Item item = new Item("Hand Grenade");
    itemList.add(item);
    
    int index = itemList.indexOf(item);
    if( index != -1 ){
      System.out.println("The item is in index " + index);
    
      // Remove the item and store it in a variable
      Item removedItem = itemList.remove(index);
      System.out.println("We removed " + removedItem.getType() + " from the list.");
    }
    

    【讨论】:

    • 哇。这是我应该写的答案,+1 的努力。
    • 感谢您的帮助。但它显示在项目中添加这些行后类型无法解析为变量
    • 哦,我刚刚解决了这个问题。非常感谢您的帮助~
    【解决方案2】:

    您必须覆盖您要放入的项目的.equals 方法。默认情况下,Java 通常会比较对象引用,而不是对象的值。

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 2012-12-04
    • 2012-10-17
    • 2015-03-15
    • 2021-04-27
    • 2013-04-22
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多