Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest and most efficient way to traverse an ArrayList in reverse

Is there a quicker, more efficient means of doing so than using a ListIterator?

ListIterator<Integer> itr = list.listIterator(list.size());
while(itr.hasPrevious()){
    System.out.println(itr.previous());
}
like image 760
mre Avatar asked May 31 '11 13:05

mre


People also ask

What is the way to get reverse of an ArrayList?

An arraylist is created that takes only Employee(user defined) Objects. These objects are added to the arraylist using add() method. The arraylist is reversed using In-built reverse() method of Collections class. The printElements() static method is used only to avoid writing one more class in the program.

How do you reverse a List in java traverse?

We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.

Which is used to traverse an ArrayList?

The iterator can be used to iterate through the ArrayList wherein the iterator is the implementation of the Iterator interface. Some of the important methods declared by the Iterator interface are hasNext() and next().


1 Answers

Depending on the implementation of the List and ListIterator the following may be (slightly) quicker.

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

This may be faster for an ArrayList but it will almost certainly be slower for a LinkedList.

Your best bet is to just use the iterator.

It is almost certain that whatever work you are doing in the loop will negate any performance gained by not using the iterator.

like image 170
jjnguy Avatar answered Nov 04 '22 10:11

jjnguy