I have the following method in a program of mine:
/**
* Returns the index of the first occurrence of the specified item.
* If the specified item in not part of the list
* the method indexOf returns -1
*
* @param item
* @return index of the first occurrence of the item; -1 if the word was not found.
*/
public int indexOf(String item) {
int index = 0;
//While we haven't reached the end of the list
while(head != null) {
//If the items are equal return true
if(head.item == item) {
return index;
}
//Set the head to the next and increment the index
head = head.next;
index++;
}
return -1;
}
While everything looks correct to me (other than needing to change head.item == item to head.item.equals(item)), it is not giving me the correct index.
While it does give me -1 for an element that is not in the lest, every time it is returning 0 as the index for an element that is in the list and I cannot figure out for the life of me why index is not incrementing.
Any input would be greatly appreciated! Thanks