• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 382
  • Last Modified:

backward traversal is not possible in enhance for loop

Hi,

I read as backward traversal is not possible in enhanced for loop. I was not clear on that. Any ideas, resources, links, sample code highly appreciated. thanks in advance.
0
gudii9
Asked:
gudii9
3 Solutions
 
objectsCommented:
you can't do the following with the enhanced for

for (int i=list.size()-1; i>=0; i--) {
   Object next = list.get(i);
   ...

It only allows you to iterate from start to end
0
 
Sathish David Kumar NArchitectCommented:
This is one of the main disadatage of  enhance for loop ! we cant go backward .
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
Jim CakalicSenior Developer/ArchitectCommented:
As stated, the enhanced for syntax allows only forward traversal. However, backward traversal isn't particularly difficult (although perhaps inefficient):

Backwards traversal of an existing collection 'c' of class 'Type':
List<Type> temp = new ArrayList<Type>(c);
Collections.reverse(temp);
for (Type x : temp) {
    // do whatever
}

Open in new window

Backwards traversal of an existing array 'a' of class 'Type':
List<Type> temp = Arrays.asList(a);
Collections.reverse(temp);
for (Type x : temp) {
    // do whatever
}

Open in new window

In each case a new List object is constructed that duplicates the references of the original collection/array. The order of the references is then reversed before using the new List as the Iterable of the for loop.

Regards,
Jim
0
 
gudii9Author Commented:
>>As stated, the enhanced for syntax allows only forward traversal. However, backward traversal isn't particularly difficult (although perhaps inefficient):

can we do reverse traversal. please advise
0
 
objectsCommented:
> can we do reverse traversal. please advise

I showed how in my first comment
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now