【问题标题】:How to get previous element in a LinkedList?如何获取 LinkedList 中的前一个元素?
【发布时间】:2014-08-05 19:38:11
【问题描述】:

我正在使用LinkedList,我想获取上一个(和下一个)元素,但不知道如何处理。

我的链表:

LinkedList<Transaction> transactions = transactionRepository.findAll();

我正在搜索此交易:

Transaction targetTransaction = new Transaction("admin", new Date(), 5);

我想做什么:

for (Transaction transaction : transactions) {
    if (transaction.equals(targetTransaction)) {
        System.out.println("Previous transaction: " + transaction.getPrev());
    }
}

transaction.getPrev() 部分不起作用,因为我的 Transaction 对象没有这样的方法。

问题:如何正确地从LinkedList中获取“previous”对象?

【问题讨论】:

  • 如果你使用双向链表,这是最简单的。
  • 如果你维护你所在的索引,你可以使用它来获取上一个。
  • 显式使用ListIterator,而不是增强的for循环
  • 谢谢大家,伙计们。我一直在寻找使用 LinkedList 的优雅解决方案。将其作为数组迭代是我的 B 计划。现在看来我不必这样做了。

标签: java linked-list


【解决方案1】:

增强的for循环在后台使用Iterator,并且这个接口没有提供任何方法去上一个元素。请改用LinkedList#listIterator

ListIterator<Transaction> li = transactions.listIterator(0);
while (li.hasNext()) {
    //your logic goes here

    //if you need to go to the previous place
    if (li.hasPrevious()) {
        li.previous();
        //further logic here...
    }
}

【讨论】:

    【解决方案2】:

    在浏览列表时跟踪之前的Transaction

    Transaction prev = null;
    for (Transaction transaction : transactions) {
        if (transaction.equals(targetTransaction)) {
            System.out.println("Previous transaction: " + (prev = null ? "[none]" : prev));
        }
        prev = transaction;
    }
    

    【讨论】:

    • 谢谢!我认为接受的答案更适合我的情况。但是非常感谢您的意见。
    【解决方案3】:

    手动跟踪最后一个元素。

    Transaction last = null;
    for (Transaction transaction : transactions) {
        if (transaction.equals(targetTransaction)) {
            System.out.println("Previous transaction: " + last);
        }
        last = transaction;
    }
    

    【讨论】:

    • 问题中指出transaction.getPrev()不存在。您希望它如何编译?
    • @Jashaszun 忘记更新println。现已修复。
    • 你的答案现在和我的完全一样(减去一点点错误检查)......
    • 虽然我猜基于那个元问题,我们的两个答案都应该被同等投票,所以我想我们很好。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-27
    • 2014-09-22
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多