我正在使用a LinkedList,我想获得前一个(和下一个)元素,但不知道如何处理它.
我的链表:
LinkedList<Transaction> transactions = transactionRepository.findAll();
Run Code Online (Sandbox Code Playgroud)
我正在寻找此交易:
Transaction targetTransaction = new Transaction("admin", new Date(), 5);
Run Code Online (Sandbox Code Playgroud)
我想做的事:
for (Transaction transaction : transactions) {
if (transaction.equals(targetTransaction)) {
System.out.println("Previous transaction: " + transaction.getPrev());
}
}
Run Code Online (Sandbox Code Playgroud)
该transaction.getPrev()部分不起作用,因为我的Transaction对象没有这样的方法.
问题:如何从LinkedList中正确获取"previous"对象?
Lui*_*oza 16
在后台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...
}
}
Run Code Online (Sandbox Code Playgroud)