Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get previous element in a LinkedList?

I am using a LinkedList and I want to get the previous (and the next) element, but not sure how to approach that.

My linked list:

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

I am searching for this transaction:

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

What I want to do:

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

The transaction.getPrev() part does not work, because my Transaction object does not have such method.

Question: how to correctly obtain the "previous" object from the LinkedList?

like image 410
anton1980 Avatar asked Aug 05 '14 19:08

anton1980


2 Answers

Enhanced for loop uses Iterator behind the scenes, and this interface doesn't provide any method to go to the previous element. Use LinkedList#listIterator instead:

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...
    }
}
like image 59
Luiggi Mendoza Avatar answered Oct 07 '22 08:10

Luiggi Mendoza


Keep track of the previous Transaction as you go through the list.

Transaction prev = null;
for (Transaction transaction : transactions) {
    if (transaction.equals(targetTransaction)) {
        System.out.println("Previous transaction: " + (prev = null ? "[none]" : prev));
    }
    prev = transaction;
}
like image 23
Jashaszun Avatar answered Oct 07 '22 08:10

Jashaszun