I’m trying to remove an object from an arraylist in java using android studio.
public class ToDoListManager {
private List<ToDoItem> items;
public ToDoListManager() {
items = new ArrayList<ToDoItem>();
items.add(new ToDoItem("Get Milk", false));
items.add(new ToDoItem("Walk the dog", true));
items.add(new ToDoItem("Go to the gym", false));
}
public List<ToDoItem> getItems() {
return items;
}
public void addItem(ToDoItem item) {
items.add(item);
}
public void removeItem(ToDoItem item) {
items.remove(item);
}
}
I’ve been calling the removeItem function from a keypress
When I add, let’s say "test" to the array, it successfully adds it using items.add(item), however when I try items.remove(item) given the same string, it won’t work.
It works if I do items.remove(1)
, but not if I do items.remove("test")
How could I fix this? I’ve tried many different ways. Thanks.
2
Answers
The "remove" methods implemented in the various interfaces that make up ArrayList take different arguments and do very different things.
If you look at the "List interface" there are two methods
If you want to use the boolean remove(Object o); method ie remove an Object you need to make sure the "equals" method is going to work in "ToDoItem". So what does your equals method look like in ToDoItem?
Your
items
only accepts theToDoItem
objects.So,
items.remove("test")
will not work. Here"test"
is a String object.But
items.remove(1)
will work because here you are passing anindex
value as a parameter toremove()
method. So the object fromitems
at the specified index will be removed.To remove the specified object from
items
list, you need to pass theToDoItem
object as a parameter.Read more: How To Remove An Element From An ArrayList?
Note: If you want to compare two
ToDoItem
objects by its data members values, override the equals method inToDoItem
.