This is probably a noobish question but, i have been working on this project and couldn't get it to work. I got frustrated and experimented around and got it to work somehow. The change i made was i added a -1 to numOfItem.
I would really appreciate if someone could explain to me why this worked. My head is not really reading the code properly i believe. I am under the impression that if i am removing an item on the last index, it should throw an error.
for (int j = i; j < numOfItem - 1; j++)
This code belongs to a nested for loop in this method:
//Removes only a single instance of the specified item.
//If the item doesnt exist in the bag, it returns false
public boolean remove(Object item) {
for (int i = 0; i < numOfItem; i++) {
if (stuff[i].equals(item)) {
for (int j = i; j < numOfItem - 1; j++)
stuff[j] = stuff[j + 1];
stuff[numOfItem - 1] = null;
numOfItem--;
return true;
}
}
return false;
}
numOfItem is set to 0, when an object bag is initialized, as to signify there are 0 items in the bag, however the bag is given a max capacity (user input) when initialized. If any more info is needed, please let me know. Thanks in advance.
Your code it trying to remove an element from an array if it is found using the following steps:
Step 1 :
Find the element.
Step 2 :
a) If not found, return false;
b) If found, shift all the elements to the left from the index where the element is found.
c) Set the last index of array as null.
In the Step 2 b) shift is done by:
for(int j = i; j < numOfItem - 1; j++)
stuff[j] = stuff[j + 1];
In this above code, you need to iterate for loop till second last index only, because the last index needs to be set as null to decrement the array size after deleting the element. If you try to iterate on last index, then stuff[j+1]
will throw ArrayIndexOutOfBoundException
. Thats why numOfItem -1
works.