Using for(int i = 0; i < str.length; i++) I can easily detect if the loop is at the end.
But I how can I know if I’m using for or for each.
for(String str : arrayString){
if(End of for) //Do something if the end of the loop
}
The reason I use for(:) instead of for(;;) is that str is actually a large Object which I need to use that property for another loop inside that loop. And I don’t like using much object.get(index).getProperty It just also for convenience to me in doing the coding. That’s why I want to know if the for(:) loop is at the last index.
UPDATE
My interim solution is to assign a int variable that will hold the number of iteration. Then check if the variable is equal to the length of the str.length.
One option would be to write your own iterator implementation which exposed, at each point, properties of first, last, index and value.
I’ve done the same thing for .NET, and it was far from tricky. In Java it would be even easier, as you could use the
hasNext()method of the original iterator to determine whether or not it’s the last element. The code would look something like this (completely untested):