Reputation: 39
I'd like to check if an element is removed from a list using java.
The first method is to remove the element, and then I create a new method to check if it is deleted:
public void removeElement(int index){
try {
element.remove(index);
} catch(IndexOutOfBoundsException e){
System.out.println("Please enter an index number between 0 and "+e);
}
}
public void removeElement (Element element) {
boolean removed;
if(element==null) {
removed=true;
}
else {
removed=false;
}
No error appears, just a warning saying "The value of the local variable removed
is not used."
Upvotes: 2
Views: 1630
Reputation: 15433
Given the list :
List<Element> myList = new ArrayList<>();
You could change your removeElement()
method to the following:
public boolean removeElement (Element element) {
return myList.remove(element);
}
Here if the element was successfully removed, it would return true
else it would remove false
. (Also since this a custom class you need to override the equals()
and hashcode()
methods.
You are receiving this warning
"The value of the local variable removed is not used."
because in removeElement (Element element)
you are not returning the value of the variable removed
so its value is not being used anywhere.
Upvotes: 1
Reputation: 2119
You can use list.contains()
to check if the Element
exists in the List
. But for that to work, your class Element
needs to have equals
and hashcode()
methods over-ridden because contains
internally uses them to check for the equality.
Upvotes: 0