【问题标题】:Remove object from Arraylist Java, only working in specific scenarios从 Arraylist Java 中移除对象,仅适用于特定场景
【发布时间】:2022-01-10 07:54:24
【问题描述】:

我正在尝试使用 android studio 从 java 中的数组列表中删除一个对象。

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);
    }
}

我一直在通过按键调用 removeItem 函数

当我将“test”添加到数组时,它使用 items.add(item) 成功添加它,但是当我尝试给定相同字符串的 items.remove(item) 时,它不起作用。 如果我做items.remove(1),它会起作用,但如果我做items.remove("test"),它就不行

我该如何解决这个问题?我尝试了很多不同的方法。谢谢。

【问题讨论】:

  • 您无法使用此代码调用 items.remove(1) 或 items.remove("test"),因此您没有提供准确的信息

标签: java android-studio arraylist


【解决方案1】:

在组成 ArrayList 的各种接口中实现的“删除”方法采用不同的参数并做不同的事情。

如果你看一下“列表接口”有两种方法

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);
    ...
}

如果您想使用 boolean remove(Object o); 方法,即删除一个对象,您需要确保“equals”方法在“ToDoItem”中有效。那么你的 equals 方法在 ToDoItem 中是什么样子的呢?

【讨论】:

    【解决方案2】:

    您的items 只接受ToDoItem 对象。

    因此,items.remove("test") 将不起作用。这里"test"是一个String对象。

    但是items.remove(1) 会起作用,因为在这里您将index 值作为参数传递给remove() 方法。所以items在指定索引处的对象将被删除。

    要从items 列表中删除指定对象,您需要将ToDoItem 对象作为参数传递。

    阅读更多:How To Remove An Element From An ArrayList?

    注意:如果您想通过其数据成员值比较两个ToDoItem 对象,请使用ToDoItem 中的override the equals 方法。

    【讨论】:

    • 我尝试将它作为对象传递,但它仍然不起作用。我最终改变了我的程序的工作方式,谢谢!
    • 您是否正在创建一个新对象并将其传递给remove() 方法?如果是,您是否在 ToDoItem 类中覆盖了 equals() 方法?如果您正在创建一个新对象(即使具有相同的参数值)并将其传递给 arraylist remove 方法,它将不起作用。默认的equals() 方法比较对象引用是否相等。
    • ArrayList remove 方法使用此条件删除对象。 (o==null ? get(i)==null : o.equals(get(i)))你需要重写equals()方法(然后hashcode()方法到maintain the contract)来比较对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 2012-01-21
    • 1970-01-01
    • 1970-01-01
    • 2013-08-23
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多