简体   繁体   English

从arraylist java中删除项目

[英]removing item from arraylist java

I am trying to compare weather an item is contained within the arrayList and if it is then remove it. 我试图比较一个项目包含在arrayList中的天气,如果是,则删除它。 Im not sure weather I have to implement my own equals method or not, this is my code but it isn't working to remove the correct item. 我不确定天气我必须实现我自己的equals方法,这是我的代码,但它无法删除正确的项目。

  public boolean removeItem(Item item) {

    for(int i = 0; i < items.size(); i++) {

        if (items.get(i).equals(item)) {
            items.remove(item);
            return true;
        } 


    }
    return false;
}

You can safely remove items from a Collection using Iterator 您可以使用Iterator安全地从Collection删除项目

public boolean removeItem(Item item) {    
  Iterator<Item> it = items.iterator();
  while (it.hasNext()) {
     Item i = it.next();
     if(i.equals(item)) {
       it.remove();
       // remove next line if you want to remove all occurrences `item`
       return true; 
     }      
  }
  return false;
}

You could also just call 你也可以打电话

items.remove(item);

ArrayList#remove(Object) will do exactly that! ArrayList #remove(Object)就是这样做的! But this works only if you have overridden the equals method of Item . 但这只有在你重写了Itemequals方法时才有效。 If You want to remove all elements, will need a loop: 如果要删除所有元素,则需要循环:

public int remove(Item item) {
    int i = 0;

    while(list.remove(item)) {
        i++;
    }

    return i;
}

this will return the amount of items that have been removed 这将返回已删除的项目数量

Removes the first occurrence of the specified element from this list, if it is present. 从此列表中删除指定元素的第一个匹配项(如果存在)。 If the list does not contain the element, it is unchanged. 如果列表不包含该元素,则不会更改。 More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). 更正式地,删除具有最低索引i的元素,使得(o == null?get(i)== null:o.equals(get(i)))(如果存在这样的元素)。 Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call). 如果此列表包含指定的元素,则返回true(或等效地,如果此列表因调用而更改)。

I think you want contains not equals`. 我想你想要包含不等于。 You don't even need to loop it. 你甚至不需要循环它。 That's the magic of the method. 这是该方法的神奇之处。

public boolean removeItem(Item item) {

    if (items.contains(item)){
        items.remove(item);
    }
    return false;  // I have no idea why you want to return false.
                   // I'll just leave it there
}

Yes you have to override equals in your class.Compare every single attribute and when one of them dont equals the other, then return false. 是的,你必须在你的类中重写equals。比较每个属性,当其中一个不等于另一个时,然后返回false。 If you use eclipse for example, you can let it create the equals method for your class. 例如,如果你使用eclipse,你可以让它为你的类创建equals方法。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM