简体   繁体   中英

Java - Removing element from a Linked List using iterator

I have a program that reads in entries that are added to a linked list, and the method below which deletes entries. Currently, the method seems to go through the list and, once it finds the chosen entry, deletes it as well as all of the entries before it , instead of just the individual entry. Removing the break; makes the method just remove all entries in the list.

LinkedList<Entry> entryList = new LinkedList<Entry>();
ListIterator<Entry> entryIterator = entryList.listIterator();

public void deleteEntry(int number) {
    while(entryIterator.hasNext()) {
        Entry entry = entryIterator.next();
        if((entry.getNumber() == number)) {
                entryIterator.remove();
                //break;
        }
    }
}

I have a feeling that the problem is elsewhere but can't figure it out - i'm pretty new to java. Thanks!

Looks like

entry.getNumber() == number

is always TRUE, so problem is not in this code but somewhere else.

Maybe Entry number defined as static or all elements in the list are the same object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM