Looping through a Collection object
This example shows how to iterate through an object which implements the Collection interface. Here we use and ArrayList but the same code can roughly be applied to other classes that implements the Collection interface since they'll also implement the Iterable interface. In the example code we use three different ways that do exactly the same thing, namely to loop through the elements of the list and print them out. First we create the ArrayList using generics which means that we specify of what type the elements of the list should be. In this case we specify that the elements should be of type String. In the first two iteration examples we call the iterator() method to get the reference to the objects iterator. Once obtained, we can loop for as long as its hasNext() method returns true. The last iteration example shows the relatively new way to loop, introduced in Java 5. Basically we declare a variable called element and say that for each element in the array, assign its value to the variable element. |
import java.util.ArrayList; import java.util.Iterator; /** * * @author javadb.com */ public class Main { /** * Example of iterating through a Collection object */ public void iterateCollection() { ArrayList<String> list = new ArrayList<String>(); list.add("Monday"); list.add("Tuesdag"); list.add("Wednesday"); list.add("Thursday"); list.add("Friday"); list.add("Saturday"); list.add("Sunday"); Iterator<String> iterator = null; //Example 1: iterator = list.iterator(); while (iterator.hasNext()) { String element = iterator.next(); System.out.println(element); } //blank line System.out.println(); //Example 2: for (iterator = list.iterator(); iterator.hasNext(); ) { String element = iterator.next(); System.out.println(element); } //blank line System.out.println(); //Example 3: for (String element : list) { System.out.println(element); } } /** * @param args the command line arguments */ public static void main(String[] args) { new Main().iterateCollection(); } } |
Naturally, the output of the code is: Monday Tuesdag Wednesday Thursday Friday Saturday Sunday Monday Tuesdag Wednesday Thursday Friday Saturday Sunday Monday Tuesdag Wednesday Thursday Friday Saturday Sunday |
Search for code examples on this site
