简体   繁体   English

Java-使用迭代器从链接列表中删除元素

[英]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. 我觉得问题出在其他地方,但无法解决-我对Java很陌生。 Thanks! 谢谢!

Looks like 看起来像

entry.getNumber() == number

is always TRUE, so problem is not in this code but somewhere else. 始终为TRUE,因此问题不在此代码中,而在其他地方。

Maybe Entry number defined as static or all elements in the list are the same object. 也许条目号定义为静态,或者列表中的所有元素都是同一对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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