Friday, June 15, 2012

for loops - arrays and lists

Dedicated to my coworkers who are transitioning from HIBOL to Java. I respect your courage.

So the basic gist of this post is that all of the following examples do basically the same thing. That way we can see what's similar and different. Hopefully this will help us all better understand the for loop.

while - loop through an array

        
        String[] names = new String[] { "Joe", "Sally", "Henry" };
        
        int i = 0;
        while (i < names.length) {
            System.out.println(names[i]);
            i++;
        }

run:
Joe
Sally
Henry

for - loop through an array

        
        String[] names = new String[] { "Joe", "Sally", "Henry" };
        
        for (int i = 0; i < names.length; i++) {
            System.out.println(names[i]);
        }

run:
Joe
Sally
Henry

for/in - loop through an array

        
        String[] names = new String[] { "Joe", "Sally", "Henry" };
        
        for (String s : names) {
            System.out.println(s);
        }

run:
Joe
Sally
Henry

while - loop through a list

        

        java.util.List names = new java.util.ArrayList();
        names.add("Joe");
        names.add("Sally");
        names.add("Henry");

        int i = 0;
        while (i < names.size()) {
            System.out.println(names.get(i));
            i++;
        }

run:
Joe
Sally
Henry

for - loop through a list

        

        java.util.List names = new java.util.ArrayList();
        names.add("Joe");
        names.add("Sally");
        names.add("Henry");

        for (int i = 0; i < names.size(); i++) {
            System.out.println(names.get(i));
        }

run:
Joe
Sally
Henry

for/in - loop through a list

        

        java.util.List names = new java.util.ArrayList();
        names.add("Joe");
        names.add("Sally");
        names.add("Henry");

        for (String s : names) {
            System.out.println(s);
        }

run:
Joe
Sally
Henry


note that the for/in loop syntax is exactly the same for looping through an array as it is for looping through a list:

        
        for (String s : names) {
            System.out.println(s);
        }


Technically, any class that implements the Iterable interface can be used in a for/in statement, but we'll save that discussion for another day :)

No comments:

Post a Comment