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());
}
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.
We can iterate the list in reverse order in two ways: Using List. listIterator() and Using for loop method.
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With