【问题标题】:how can I get the next object on my linkedlist?如何获得链表上的下一个对象?
【发布时间】:2018-12-17 19:02:57
【问题描述】:

我在Java 中有一个LinkedList 对象,我想遍历它,当我在那里找到一个特定对象时 - 我想获取下一个对象(紧邻第一个对象的那个) )。

我认为这会解决这个问题:

listIterator = items.listIterator();
while (listIterator.hasNext() && listIterator.previous().getCode().equals(search.getCurrentCode())) {

    item = listIterator.next();
    result.setCurrentCode(item.getCode());
    break;
}

但我遇到了错误:

java.util.NoSuchElementException: null

我认为是因为使用了.previous,但我不知道如何正确处理,那我该如何解决呢?我正在使用previous,但我想要的是使用当前元素 - 我认为这是由.previous 处理的,但显然不是。

【问题讨论】:

  • 这个问题有点难以理解,至少对我来说是这样。您能否举一个此类列表的示例以及您想对它做什么?
  • 您使用LinkedList而不是ArrayList的任何具体原因?在几乎所有情况下,人们都会倾向于后者。

标签: java linked-list listiterator


【解决方案1】:

您当前的代码失败,因为您在开始迭代项目之前调用了之前的代码。通过listIterator.next(); 调用完成迭代。 你可以试试下面的代码。

while (listIterator.hasNext()){
   // iterate always
   item = listIterator.next();
   // if found and an element still exist
   if(item.getCode().equals(search.getCurrentCode() && listIterator.hasNext()){
      // get the next element
      item = listIterator.next();
      result.setCurrentCode(item.getCode());
      break;
   }
}

【讨论】:

    【解决方案2】:

    试试这个:

    listIterator = items.listIterator();
    // listIterator.previous() does not exist in first iteration
    while (listIterator.hasNext()) {
    // you can compare previous value if it exist
    if(listIterator.hasPrevious() && listIterator.previous().getCode().equals(search.getCurrentCode())){
        item = listIterator.next();
        result.setCurrentCode(item.getCode());
        break;
    }
    }
    

    【讨论】:

      【解决方案3】:

      首先,我建议使用ArrayList 而不是LinkedList,因为前者几乎总是更好的选择。 see this post 了解更多信息。

      您绝对可以通过典型的 for 循环或增强的 for 循环来做到这一点,但我想说明一种从 JDK9 开始称为 dropWhile 的新方法,它可以帮助您实现这一要求:

      假设,你有你的ArrayList。你可以这样做:

      myList.stream()
            .dropWhile(c -> !c.getCode().equals(search.getCurrentCode()))
            .skip(1) // get the object to the right of the matched item
            .findFirst() // retrieve this object
            .ifPresent(s -> result.setCurrentCode(s.getCode())); // apply the logic based on the found object
      

      【讨论】:

        猜你喜欢
        • 2020-06-12
        • 2015-06-17
        • 2016-05-05
        • 1970-01-01
        • 2021-02-02
        • 2015-12-19
        • 2012-10-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多