java - 在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(?);
}
解决方案
该方法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 循环中调用是有条件的不安全的;它会导致一个ConcurrentModificationException
if 循环之后继续。
或者,您可以像这样实现它:
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
。
推荐阅读
- c - C - 打印行和列
- php - 如何制作一个我可以通过 js 和 php 访问的动态 xml 文件
- jquery - 当我将一个值插入到
- ,我使用 jQuery 创建的,该值出现在不在该点旁边的另一行中,看起来不太好
- c# - 用变量否定“is”运算符仅适用于“!” 但不是'== false'
- android - A/位图:错误,无法在此处访问无效/释放的位图!A/brutx.mymodeap: runtime.cc:655] 运行时中止
- python-3.x - 交互式 Python 示例重定向 URL?
- android - android可以为MD5抛出NoSuchAlgorithmException吗
- python - 我如何从 python 数据集中的文本文件中读取数据并在其上应用矩阵
- python - sybase 到 sql 服务使用炼金术
- matlab - 在 colab 中使用 octave 运行 .cu 文件