J (banana) wrote in java_dev,
J
banana
java_dev

Looping backwards

I just came across a nice syntactic trick for looping backwards over an array:
public class Decr {
   public static void main( String[] args ) {
      char[] array = { 'a', 'b', 'c' };

      // Traditional way
      for ( int i = array.length - 1; i >= 0; i-- ) {
         System.out.println( array[ i ] );
      }

      // "Start at the end, i goes to zero"
      for ( int i = array.length; i --> 0;  ) {
         System.out.println( array[ i ] );
      }
   }
}
It might look as if I invented an operator, but i --> 0 would normally be written as i-- > 0

BTW, what happened to java_dev? It used to be lively here, but no one posts any more. Did all the Java developers leave LJ?
  • Post a new comment

    Error

    default userpic

    Your reply will be screened

    Your IP address will be recorded 

  • 7 comments