Home > Blockchain >  Remove object from Arraylist Java, only working in specific scenarios
Remove object from Arraylist Java, only working in specific scenarios

Time:12-04

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.

CodePudding user response:

The "remove" methods implemented in the various interfaces that make up ArrayList take different arguments and do very different things.

ArrayList.remove signature is

public E remove(int index) 

It removes from the position in the list so it's going to work if the list has more than "index" items. So when you call it with an integer this gets used and works.

List.remove signature is

boolean remove(Object o);

Removes an object from the list if the object equals an object in the list. So when you pass it a string ie "test" this cannot work because "test" is not a ToDoItem so the equals comparison fails.

If you want to use the "List.remove" 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?

CodePudding user response:

Your items only accepts the ToDoItem 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 an index value as a parameter to remove() method. So the object from items at the specified index will be removed.

To remove the specified object from items list, you need to pass the ToDoItem 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 in ToDoItem.

  • Related