如何在给定itemNum的ArrayList中删除Item?

时间:2015-03-20 10:52:20

标签: java object arraylist casting

我想删除用户将输入的ItemNo项目。如何检查是否存在此项目的项目?然后我怎么把它删除?以下是我到目前为止,我需要添加CompareTo()方法吗?

项目类别:

public class Item {

public int itemNo;
public String itemName;
public double itemPrice;
public int itemQuantity;

Item(int number, String name, double price, int quantity)
{
itemNo=number;
itemName=name;
itemPrice=price;
itemQuantity=quantity;
}

删除方法:

 public T remove(int givenPosition) {
     T result = null; 
     if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
     assert !isEmpty();
     result = list[givenPosition - 1]; 
     if (givenPosition < numberOfEntries)
                  removeGap(givenPosition);
               numberOfEntries--;
     } // end if
     return result; 

         } // end remove

包含方法:

 public boolean contains(T anEntry) {
     boolean found = false;
     for (int index = 0; !found && (index < numberOfEntries); index++) {
     if (anEntry.equals(list[index])) 
         found = true;
     }//end for
     return found;
     } // end contains

等于方法:

public boolean equals(Object object){
        Item item = (Item) object;
        if(itemNo == item.itemNo)
            return true;
        return false;
    }

4 个答案:

答案 0 :(得分:3)

好的,你正在试图分离逻辑,但我会给你解决你的问题的代码片段。

Item item = new Item(10 , "Item1", 50 , 100);
Item item2 = new Item(20 , "Item2", 50 , 100);
Item item3 = new Item(30 , "Item3", 50 , 100);

List<Item> itemList = new ArrayList<Item>();
itemList.add(item1);
itemList.add(item2);
itemList.add(item3);

public void removeItem(int itemNo){
       Iterator<Item> it = itemList.iterator();
       while(it.hasNext){
         if(item.next().itemNo == itemNo){
            it.remove;
            break;
         }
    }
}

答案 1 :(得分:3)

由于Java8任何Collection(如List)都有removeIf(Predicate<? super E> filter)方法,可以删除项匹配过滤器。所以你的代码看起来像

list.removeIf(item -> item.getItemNo() == x );//where x is value you want to remove

答案 2 :(得分:1)

private void removeObjectWithNumber(int number) {
    for (int i = 0; i < list.size(); i++) {
        Item item = list.get(i);
        if (item.getItemNo() == number) {
            list.remove(i);
            return;
        }
    }
}

答案 3 :(得分:0)

使用ArrayList:

添加:

ArrayList<Item> mList = new ArrayList<Item>();
mList.add(new Item(101, "Television", 20000, 4));
mList.add(new Item(102, "Mobile", 6000, 4));

删除:

mList.remove(i /* index */);

包含:

    // override equals method in class
    @Override
  public boolean equals(Object v) {
        boolean retVal = false;

        if (v instanceof A){
            A ptr = (A) v;
            retVal = ptr.itemNo.longValue() == this.itemNo;
            // if you want to check more then you can do
            //  retVal = ptr.itemName.toString().equals(this.itemName.toString());
// further same for itemPrice, itemQuantity
        }

     return retVal;
  }