java.util.NoSuchElementException在对ArrayList执行操作时发生。

huangapple 未分类评论46阅读模式
英文:

java.util.NoSuchElementException occuring while performing operation on arraylist

问题

我想根据第二个列表中的某些字符串匹配筛选第一个列表。

private void getFilteredList(List<String> fileLst, List<OrderDetailsDTO> msisdnList) {
    Iterator<String> it = fileLst.iterator();
    while (it.hasNext()) {
        for (OrderDetailsDTO item : msisdnList) {
            if (it.next() != null && !it.next().contains(item.getMsisdn())) {
                it.remove();
            }
        }
    }
}
英文:

I want to filter the first list based on some string match from second list.

  private void getFilteredList(List&lt;String&gt; fileLst, List&lt;OrderDetailsDTO&gt; msisdnList) {
    Iterator&lt;String&gt; it = fileLst.iterator();
    while(it.hasNext()){
      for(OrderDetailsDTO item: msisdnList){
        if(it.next() != null &amp;&amp; ! it.next().contains(item.getMsisdn())){
          it.remove();
        }
      }
    }
  }

答案1

得分: 0

你正在执行两次 it.next()。一旦执行了 it.hasNext(),你可以直接执行 it.next().contains(item.getMsisdn()),而不需要检查 it.next() != null。

it.next()

返回:
迭代中的下一个元素

抛出:
NoSuchElementException - 如果迭代没有更多元素

因此,在调用 it.next() 之前,应始终调用 it.hasNext()。

请查看
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--

英文:

you are doing it.next() twice. Once you have performed it.hasNext() you can directly perform it.next().contains(item.getMsisdn()) instead of checking it.next() != null.

it.next()

Returns:
the next element in the iteration

Throws:
NoSuchElementException - if the iteration has no more elements

So you should always call it.hasNext() before calling it.next();

Please check
https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#next--

huangapple
  • 本文由 发表于 2020年4月10日 16:34:20
  • 转载请务必保留本文链接:https://java.coder-hub.com/61136665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定