I have a method that is supposed to delete an InventoryItem (i) in an array list (iList) when part of the description of that InventoryItem is entered. The method has to return the item that was deleted, and I'm unsure of how to do this. Here's my code so far.
public InventoryItem deleteInventoryItem(String descriptionIn) {
int index = -1;
boolean result = false;
for (InventoryItem i : iList) {
if (i.getDescription().toLowerCase().startsWith(descriptionIn.toLowerCase())) {
index = (iList.indexOf(i));
result = true;
}
if (index >= 0) {
iList.remove(index);
}
}
return null;
}
I can't use an iterator. [...] I need to use a for each loop
Here's one way:
public InventoryItem deleteInventoryItem(String descriptionIn) {
for (InventoryItem item : iList)
if (item.getDescription()
.toLowerCase()
.startsWith(descriptionIn.toLowerCase())) {
iList.remove(item);
return item;
}
}
return null;
}
Note that this removes at most one object from the list. If there are multiple matches, only the first match will be removed.
If I simply wanted to find and return an object instead of deleting it, [...]
Then you simply skip the iList.remove(item)
row.
But even better would be to split up the methods as follows:
public InventoryItem findInventoryItem(String descriptionIn) {
for (InventoryItem item : iList)
if (item.getDescription()
.toLowerCase()
.startsWith(descriptionIn.toLowerCase())) {
return item;
}
}
return null;
}
public InventoryItem deleteInventoryItem(String description) {
InventoryItem item = findInventoryItem(description);
if (item != null)
iList.remove(item);
return item;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments