I have a question,
Here is what I need to do –
I have BankItems that are associated with numbers. I fill the list but when an objects enters that is $100 more than the lowest dollar value currently in the list, I want to delete the object that has the low value.
First – I create the list
List<BankItem> listOfBankItems = new LinkedList<BankItem>();
Later in the program I create a new BankItem object and it to the list
listOfBankItems.add(createdItem);
and after adding each item I want to check to see if the new item is $100 more than any object already in the list so I run something like this
for (int i = 0; i < listOfBankItems.size(); i++) {
int oldValue =listOfBankItems.get(i).getAmount();
int newValue = createdItem.getAmount();
int calculatedDif = newValue - oldValue;
if (calculatedDif > 100) {
listOfBankItems.remove(i);
}
}
Unfortunately, this isn’t working. I don’t know what it up. Maybe I shouldn’t use a LinkedList? Maybe my logic is way off-base. Please help.
Thanks!!!
Your most significant issue probably relates to concurrent modification. For example, if element #49 is the one to be removed, once you remove it, the next element will now be #49, but you will be checking for #50 (as
iwas still incremented) – so you’re probably missing elements from your check.There are a few ways to handle this. You could remove the
i++from yourforloop (leaving only the trailing semi-colon), then do this:Alternatively, you could use an
Iteratorand itsremove()method, which would handle this for you automatically.You can also improve the performance of this by not obtaining
newValueand recalculatingcalculatedDifon every step of the loop. Declare these 2 lines above theforloop.