Friday, December 08, 2006

Accessing Elements of a List in reverse Order

The content of this post may a silly thing but none the less i thought that there may be some people who may need it. Everyone who is dealing with List in java may be knowing about iterator for traversing the List but one facility that iterator does not provide is accessing the elements in the reverse order. For this we can use ListIterator which is a Subinterface of iterator The following code shows how to traverse list in reverse order.
consider we are having a List called testList
ListIterator itr = testList.listIterator(testList.size());
Object listEle = null;
while (itr.hasPrevious()) {
listEle = itr.previous();
}

The above loop will traverse the list in reverse order.

1 Comments:

At 8:58 PM , Blogger B.M.Rao said...

I am sorry that i forgot to mention one important thing in this blog. My List that i want to iterate cannot be modified otherwise i could well have used Collections.reverse(List list) which reverses the order of the elements in the List and then iterate over that list.

 

Post a Comment

Subscribe to Post Comments [Atom]

<< Home