java - 如何从 List<> 中删除项目?

标签 java android list arraylist

我正在开发一个应用程序,其中包含票证列表,为用户提供添加票证和删除票证选项。添加选项工作正常,但删除选项不行,这是票证列表代码

public class TicketList {

    private List<Ticket> ticketList;

    public TicketList() {
        ticketList = new ArrayList<>();
    }

    public List<Ticket> getTicketList() {
        return ticketList;
    }

    public void setTicketList(List<Ticket> ticketList) {
        this.ticketList = ticketList;
    }

    public void addTicketToList(Ticket ticket) {
        ticketList.add(ticket);
    }

    public void removeFromList(Ticket ticket) {
        ticketList.remove(ticket);
    }

    @Override
    public String toString() {
        return "TicketList{" + "ticketList=" + ticketList + '}';
    }
}

另一个 Activity 中的删除功能不起作用:

private void deleteTicket() {
    TicketList ticketList = MyPreferencesManager.getInstance(this).getTicketList();
    Ticket ticket = MyPreferencesManager.getInstance(this).getTicket();
    ticketList.removeFromList(ticket);
    MyPreferencesManager.getInstance(this).putTicketList(ticketList);
}

虽然添加功能工作正常:

private void saveTicket() {
    TicketList ticketList = MyPreferencesManager.getInstance(this).getTicketList();
    Ticket ticket = new Ticket();
    ticket.setUsername(username.getText().toString());
    ticket.setPassword(password.getText().toString());
    ticketList.addTicketToList(ticket);
    MyPreferencesManager.getInstance(this).putTicketList(ticketList);
}

谁能告诉我删除或删除功能有什么问题吗?

最佳答案

这是因为当您使用以下代码时:

ticketList.remove(ticket);

删除方法将在删除之前检查列表中是否存在确切的对象项。因此,在您尝试将其从列表中删除之前,您的工单对象可能已经更改。

详情可以从List documentation查看:

public abstract boolean remove (Object o)

Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).

您需要的可能是List.remove(int index) .

关于java - 如何从 List<> 中删除项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55208954/

相关文章:

java - 如何监听所有bundle事件?

java - 从排序的 Char 数组中删除重复项

java - 从另一个类访问时重绘进度条

android - 给定 XmlPullParser 作为输入,如何创建 LayoutInflater?

python - pandas:将列表转换为 int64index

java - 在 android 上播放本地 m3u8 文件显示 setDataSourceFD 失败。 : status=0x80000000

java - android获取当前videoview的截图

android - 查看 Firebase 上的 childEventListener 是否已完成所有数据的加载

python - 在 Python 中搜索字典列表的有效方法

python - 使用 python 将列表元素转换为连续的元组