Your function has a number of flaws.
- You are doing a reference equality check and not the value equality check. For doing a value equality check, always use the "equals" method. You won't get any compiler errors for this kind of flaws. You will get undesired output.
- Not all the control flows in your function has a return statement even though your method signature suggests a non-void return statement. This will produce a compiler error, the one that you are seeing in your code.
- You are having multiple return statements. This is neither a compiler error nor a runtime error. However from good programming practice perspective, it's not the best idea to have multiple return statements. You can do a flag based return statement at the very end.
- You are removing elements from a collection object while iterating through it. Depending on the type of the collection object you are using, it may throw a ConcurrentModificationException exception at run time. You need to use a fail-safe iterator instead if available.
I have tried to correct your program. See if this makes better sense:
public boolean deleteItem(String p) {
boolean itemFound = false;
//Assuming your myList object returns a fail safe iterator.
//If it returns a fail fast iterator instead, see the next option.
Iterator<String> iter = this.myList.iterator();
while(iter.hasNext()){
if(iter.next().equals(p)) {
iter.remove();
itemFound=true;
}
}
return itemFound;
}
The above program will work if the iterator is fail-safe. E.g. if your myList object is of type CopyOnWriteArrayList, its iterator will be fail safe. But if your myList object is of a type such a plain ArrayList, that returns a fail fast iterator, the above method will give you a CME.
If your myList collection object is of type List, you can try something as easy as:
public boolean deleteItem(String p) {
//removeAll will return true if at least 1 element is removed
return this.myList.removeAll(Collections.singletonList(p));
}
Alternately, if you are using Java 8, you can do something like following:
public boolean deleteItem(String p) {
//removeIf will return true if at least 1 element is removed
return this.myList.removeIf(item -> item != null && item.equals(p));
}
Hope this helps you a bit.