简体   繁体   English

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

[英]How can I remove a specific object from an arrayList and how can I check if it contains this object?

I have an arrayList type shopping cart. 我有一个arrayList类型的购物车。 When I add an new item into the shopping cart, I will check first if the shopping cart already has this item. 当我向购物车中添加新商品时,我将首先检查购物车中是否已有该商品。 But the cart.contains(item) method didn't work, it return false even there is a same item in the cart. 但是cart.contains(item)方法不起作用,即使购物车中有相同的商品,它也会返回false。 The second problem is I was not able to remove this item object from the shopping cart arrayList. 第二个问题是我无法从购物车arrayList中删除此项目对象。 My code shows as below: 我的代码如下所示:

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

Can anyone help me solve this problem? 谁能帮我解决这个问题? Thanks!! 谢谢!!

You will need to add a .equals method to the Item class so ArrayLists know how to compare two different objects together. 您将需要向Item类添加.equals方法,以便ArrayLists知道如何将两个不同的对象一起比较。 While we are at it we should add a hashCode method as well. 在此过程中,我们还应该添加一个hashCode方法。 This is mainly useful for Sets but always good to have it as a backup in case we need it. 这主要对Sets有用,但是在需要时最好将其作为备份。

We can use the .indexOf(Item) method to get the position of an object in the list. 我们可以使用.indexOf(Item)方法获取对象在列表中的位置。 If the number returns if -1. 如果数字返回-1。 Then it's not in the list. 那么它不在列表中。 If it is 0 or greater then it's in there and we can use the index to remove the item. 如果它是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;
  }
}

Now that we have a .equals and hashcode. 现在我们有了一个.equals和hashcode。 We can now compare them in the ArrayList. 现在,我们可以在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.");
}

您必须重写.equals项的.equals方法。默认情况下,Java通常将比较对象引用,而不是对象的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查 ArrayList 是否包含具有特定字段值的对象? - How can I check if an ArrayList contains an Object with a specific field value? 如何从ArrayList中正确删除Object? - How can I correctly remove an Object from ArrayList? 如何从Java中的arraylist返回特定的对象(索引)? - How can I return a specific object (index) from an arraylist in Java? 如何检查一组对象是否包含 object,该 object 的特定字段在 Java 中有特定值? - How can I check if a Set of objects contains an object having a specific fields with a specific value in Java? 如何在 arrayList.remove() 中获得新的 object - How can i get a new object in arrayList.remove() 如何调用Java中存储在arraylist中的特定对象的方法? - How can I call a method of a specific object that is stored in an arraylist in Java? 如何使用包含从 Arraylist 中删除 object - How to remove an object from Arraylist by using contains 如何转换ArrayList <Object> 到ArrayList <String> 或ArrayList <Timestamp> ? - How can I convert ArrayList<Object> to ArrayList<String> or ArrayList<Timestamp>? 如何在迭代时从 ArrayList 中删除 object 而不会出现“并发修改错误” - How can i remove an object from the ArrayList while iterating without getting an “Concurrent Modification Error” 如何从对象中删除装饰器? - How can I remove a decorator from an object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM