BelajarJava.Com


Looping Technique For Collection

Posted in Fundamental by on the January 14th, 2009

Take a look to the given array bellow:

int[] numbers = {1,2,3,4,5,6};

How you iterate that array? so the result of iteration will look like this:

This is number 1

This is number 2

This is number 3

..so on

This is old-style-for-loop that i use before, initialize counter, set up a terminating condition and describe how the counter may be increment. It’s classic but sometime we need it. It will be look like this:

  1. package belajarjavadotcom.post.genericloop
  2.  
  3. public class GenericLoop {
  4. public static void main(String[] args) {
  5. int[] numbers = {1,2,3,4,5,6};
  6. for(int i=0; i<numbers.length; i++) {
  7. System.out.println("This is number "+numbers[i]);
  8. }
  9. }
  10. }
  11.  

Now, start from JDK 1.5 we can simply write a new-fashion-for-looping.  We do not need to determine how many element in array before looping, we do not need to setting up termiating condition neither incremental value of the counter. It’s easy so take a look codes bellow: (more…)