java - 如何从 arrayList 中删除特定对象以及如何检查它是否包含该对象?

标签 java spring arraylist controller

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

@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;
    }
}

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

最佳答案

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

我们可以使用 .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.");
}

关于java - 如何从 arrayList 中删除特定对象以及如何检查它是否包含该对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36830424/

相关文章:

java - 在java中使用foreach循环时出现奇怪的错误

java - Java 的 ArrayList.forEach 在 while 循环内无法正常工作

java - 新创建的图形对象仅在调整框架大小后显示

java - 使用 Spring MVC 显示 Set<State>

不带 Spring Boot 的 Spring Boot 2 执行器

java - list.add 覆盖以前的对象

java - Eclipse(ZIP 发行版)SWT 链接错误

java - 如何获取给定键的值列表并将该值列表添加到新创建的列表中?

java - 使用pdfbox将透明图像插入pdf

java - 如何在Spring中为html创建 View 解析器?