Question about ArrayList for loop.

Is there a way to modify the for loop for an arraylist to start at the last index and work it's way to the first index.

Would like this line to start at last index in array instead of zero.

for (Class objName : arrayList)

I realize I can just get the size of the array and do a reverse counter with an enhanced for loop, but I would like to know if the above is possible. Thanks.

[405 byte] By [RBella] at [2007-11-26 23:48:05]
# 1
As far i know, thats the only and simplest way of doing it!
amruth_b@yahoo.co.ina at 2007-7-11 15:23:20 > top of Java-index,Core,Core APIs...
# 2

ListreverseList = new ArrayList(list);

Collections.reverse(reverseList);

for (Object item : reverseList)

{

// ...

}

ejpa at 2007-7-11 15:23:20 > top of Java-index,Core,Core APIs...
# 3
Why do you think it starts at zero?
akimotoa at 2007-7-11 15:23:20 > top of Java-index,Core,Core APIs...
# 4

That's how ArrayList's iterator method works.

for (Class x: arrayList) {...}

is roughly equivalent to

for (int i=0; i<arrayList.size(); i++) {

Class x = arrayList.get(i);

...

}

Now, to answer the original poster's question, no, I don't think it's possible

to do it without incurring extra cost (such as generating a new reversed list).

So, the only way to do it without extra cost is

for (int i=arrayList.size()-1; i>=0; i--) {

Class x = arrayList.get(i);

...

}

KathyMcDonnella at 2007-7-11 15:23:20 > top of Java-index,Core,Core APIs...
# 5

Thanks for the replys.

I kinda figured that line code not be modified. Just to let you all in on the "why", I am populating a table with the information from the array. However there is one bit of information I want reversed (i.e. element[0]'s last data to show on element[size]'s table row).I have it working exactly the way I want, but being able to reverse for(Class objName : arrayList) would save some time and be easier to read.

Again thanks to everyone.

RBella at 2007-7-11 15:23:20 > top of Java-index,Core,Core APIs...