1

In my game, I have an arraylist of item objects which have a quantity variable. My method to update the arraylist to delete items with a negative quantity and to delete duplicate occurrences is not working correctly. help much needed.

public void updateInventory() {
    // subtracting from wrong one, keeping lesser
    for(int j = 0; j < inventory.size() - 1; j++) {
        if(inventory.get(j).equals(inventory.get(j+1))) {
            inventory.get(j+1).changeQuant(-1);
            inventory.get(j).changeQuant(1);
        }
    }
      for(int i = 0; i < inventory.size(); i++) {
        if(inventory.get(i).getQuant() < 0)
            inventory.remove(i);
    }

}

The method change quant returns quant += parameter.

Ridge Haven
  • 13
  • 1
  • 4
  • 1
    Your loop and remove is incorrect, take a look in http://stackoverflow.com/questions/10714233/remove-item-from-arraylist – Viet Dec 23 '16 at 02:15
  • You need to loop over the list backwards, so that the index doesn't ever get thrown off. – 4castle Dec 23 '16 at 02:16

0 Answers0