Ricardo Sanchez Ricardo Sanchez - 26 days ago 7
Java Question

How to iterate from last to first an ArrayList?

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

Answer

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."