skip to Main Content

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


  1. 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

    public interface List<E> extends Collection<E> {
        ...
    
        // 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.
    
        public E remove(int index) 
    
        ...
        // There is a second remove method in the interface
    
        // This 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.
    
        boolean remove(Object o);
        ...
    }
    

    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?

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search