簡體   English   中英

從 ArrayList 中刪除元素 - 代碼正在跳過元素

[英]Remove elements from ArrayList - Code is skipping elements

我想要做的是循環遍歷引用某個段落的索引列表。 如果段落太短,請從列表中刪除索引。

這是我目前正在使用的代碼,在谷歌搜索之后,我嘗試接受使用迭代器的建議,但仍然沒有運氣。

    ArrayList<Content> list = anotherList;

    Iterator<Content> i = list.iterator();
    while (i.hasNext()) {

        Content element = i.next();
        int index = list.indexOf(element);

        String paragraph = getContent(index);

        if (paragraph.split(" ").length < minWordCount) {
            i.remove();
        } else {
            irrelevantFuction(index);
        }
    }

如果 i.remove() 被調用,迭代器似乎仍然會跳過元素,我理解這正是迭代器要防止的。

有人能指出我哪里出錯了嗎?

謝謝

如果您想訪問索引,則應該使用ListIterator而不是普通的Iterator ,並且即使在刪除元素時也要保持正確更新。 使用listIterator()方法獲取它,在循環中,使用nextIndex()獲取索引,使用next()獲取下一個 object,按此順序。

另外,如果您能提供幫助,請不要使用索引。 只需單獨使用 object,根據需要傳遞它,或者同時傳遞索引和元素。 無論哪種方式,都不要再次使用索引來訪問列表。

ListIterator<Content> i = list.listIterator();
int count = 0;
while (i.hasNext()) {
    int index = i.nextIndex();
    Content element = i.next();
       // ...
    }
}

不要混合list.indexOf和迭代器。 這可能會導致您出現問題。 從元素中獲取字符串(我假設Content object 有字符串,對嗎?)並使用它。

while (i.hasNext()) {

    Content element = i.next();
    String paragraph = element.yourMethodToGetTheString() // Some method...

    if (paragraph.split(" ").length < minWordCount) {
        i.remove();
    } else {
        irrelevantFuction(index);
    }
}

這行int index = list.indexOf(element); 返回正確的索引(嘗試打印它)? 也許您應該更改Content以便它可以返回它自己的段落String paragraph = element.getParagraph(); 如果您從頭到尾迭代 ArrayList,為什么需要在每一輪中調用indexOf

嘗試:

    Iterator<Content> i = list.iterator();
    int count = 0;
    while (i.hasNext()) {

        Content element = i.next();

        String paragraph = element.getParagraph();

        if (paragraph.split(" ").length < minWordCount) {
           i.remove();
        } else {
         // fixed according to comment
         int index = count++;
         irrelevantFuction(index);
       }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM