首页 > 解决方案 > 在java中的arraylist中添加最近删除的值

问题描述

我创建了另一个名为 Item 的类,它具有参数 description (string) 和 price (int)。在一个单独的类中,称为卖方,项目用于将项目列表保存给特定的卖方。一切运行都没有错误,但返回的值让我失望。

一种方法将项目添加到 ArrayList,另一种方法在“出售”后删除项目。第三种方法将刚刚删除的项目添加回数组列表。

我有两个问题,
1.如果应该有的只是被移除(出售)的物品,那么应该在 sellItem 中返回什么。
2.当唯一的参数是上面的返回值(不是描述或价格)时,我将如何添加项目。在被测试的代码中,i = s.sellItem("one-bedroom condo");与 一起给出,s.acceptReturnedItem(i);以便参数是以前使用的变量。

这是我的代码:

ArrayList <Item> items = new ArrayList <Item>();

public void addItem(String description, int price) {
    Item i = new Item(description, price);
    items.add(i); 
    return;
}
//adds item with two parameters

public Item sellItem(String description) {
    for (Item v: items) {
        if (v.getDescription() == description) {
            items.remove(v);
        }
    }
    return new Item(?); //what are we returning??? 
}

public Item acceptReturnedItem(Item x) { //where x is the returned item from above
    //Item f = new Item(addItem);      not sure if this is correct
    //items.add(f);                    would add it??
    return new Item(?);
}

标签: java

解决方案


该方法sellItem()应如下所示:

public Item sellItem( String description ) 
{
    Item retValue = null;
    for( Item v : items ) 
    {
        if( v.getDescription().equals( description ) ) 
        {
            retValue = v;
            // you need to break the loop here …
            break;
        }
    }

    if( retValue != null ) items.remove( retValue );

    return retValue;
}

items.remove()在 foreach 循环中调用是有条件的不安全的;它会导致一个ConcurrentModificationExceptionif 循环之后继续。

或者,您可以像这样实现它:

public Item sellItem( String description ) 
{
    Item retValue = null;
    for( Iterator<Item> i = items.iterator(); i.hasNext() && (retValue == null); ) 
    {
        Item v = i.next();
        if( v.getDescription().equals( description ) ) 
        {
            retValue = v;
            i.remove();
            // No break necessary here …
        }
    }

    return retValue;
}

Iterator.remove()在循环内调用是安全的。

在内部,foreach 循环看起来像第二个建议;看看界面Iterable


推荐阅读