I wonder if is possible to iterate from last to the first element in an ArrayList, if so how? The reason is because I need to remove the last element added to the list
While you can always iterate your ArrayList
using an index, like this
List<String> myList = new ArrayList<String>();
... add code to populate the list with some data...
for (int i = myList.size() - 1 ; i >= 0 ; i--) {
if (myList.get(i).equals("delete me")) {
myList.remove(i);
}
}
you would be better off using a ListIterator<T>
for the purpose of deleting items from your ArrayList
:
ListIterator<String> listIter = myList.listIterator();
while (listIter.hasNext()) {
if (listIter.next().equals("delete me")) {
listIter.remove();
}
}
List iterators can be used to iterate your list backwards, too -- like this:
ListIterator<String> listIter = myList.listIterator(myList.size());
while (listIter.hasPrevious()) {
String prev = listIter.previous();
// Do something with prev here
}
The initial index of the iterator should be equal to the index of the last element + 1. As the docs say: "An initial call to previous
would return the element with the specified index minus one."
Here is one way to do it (your reason why is a separate question):
import java.util.*;
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
ListIterator<String> iter = list.listIterator(list.size());
while (iter.hasPrevious()) {
String s = iter.previous();
System.out.println(s);
}
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