The simplest way to do this is to iterate backwards over the list. This means when you remove an element, the other elements will not get reordered. The method below demonstrates:
public void iterateBackwards()
{
List list = new ArrayList(Arrays.asList(1,2,3,4,5));
for (int i = list.size() - 1; i >= 0; --i)
{
System.out.println(list.remove(i));
}
}
{
List
for (int i = list.size() - 1; i >= 0; --i)
{
System.out.println(list.remove(i));
}
}
This prints....
5
4
3
2
1
No comments:
Post a Comment