Skip to content
Advertisement

How to remove an item from List?

I’m developing an app, which contains a list of tickets, there are add ticket and remove ticket options for the user. The add option works fine, but the remove option doesn’t, here is the ticket list code

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 + '}';
    }
}

The delete function in another activity which doesn’t work:

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

While the add function works fine:

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

Can anyone tell me what’s wrong with the deleting or removing function?

Advertisement

Answer

It is because when you’re using the following code:

ticketList.remove(ticket);

the remove method will check if there is an exact object item in the list before removing. So, your ticket object probably is already changed before you’re trying to delete it from the list.

You can see the details from 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).

What you need is probably List.remove(int index).

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement