The fastest and most efficient way to traverse an ArrayList in reverse

Is there a faster and more efficient tool than using ListIterator ?

 ListIterator<Integer> itr = list.listIterator(list.size()); while(itr.hasPrevious()){ System.out.println(itr.previous()); } 
+7
source share
5 answers

Depending on the implementation, List and ListIterator may be (slightly) faster.

 List l; for (int i = l.size()-1; i >=0; i--) { System.out.println(l.get(i)); } 

It may be faster for ArrayList , but it will almost certainly be slower for LinkedList .

It is best to use an iterator.

Almost certainly, any work that you do in a loop will negate any performance obtained by using an iterator.

+10
source

Theoretically, using a simple index-based loop can be faster with a minimum amount, since there is no overhead for calling the method for the test, but in practice it is very, very unlikely to be significant and cannot even appear at all.

More importantly, the iterator-based solution is clearer and works more efficiently with linked lists, not just ArrayLists.

+2
source

Depending on the implementation class of the list, it may be more efficient to flip the list (using Collections.reverse ), use a forward iterator, and then cancel the list again to restore it.

Please note that java.util.LinkedList is a double list, so this strategy is not needed; using hasPrevious and previous as effective as in the forward direction. This is true, I think of every implementation of the stock list in java.util.

+2
source

The solution you presented is as fast as using a regular index with an index. If you want to find an even better solution, I suggest an implementation with LinkedList, since I think this is the fastest solution.

+1
source

You can flip one line, which

Collections.reverse (list);

 ArrayList arrayList = new ArrayList(); arrayList.add("A"); arrayList.add("B"); System.out.println("Before Reverse Order : " + arrayList); Collections.reverse(arrayList); System.out.println("After Reverse : " + arrayList); 

Exit

 Before Reverse Order : [A, B] After Reverse : [B, A] 
0
source

All Articles