Tino APCS

Arrays and For-Each loops

In the previous lesson, we saw how Java's new for-each loop is useful for iterating over a Collection of objects. Because classic arrays are not objects (and thus do not implement the <Iterator> interface), you cannot directly use an Iterator on them. You can, however, use a for-each loop as shown below.

int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i: list)
    System.out.println(i);


The code reads, "for each integer i inside list... do whatever".

Because the for-each loop does not use a counter, there is no way for you to operate on the contents unless they are objects. For example, let's say you want to reset each item in the code above to zero. Well, you can't do that with a for-each loop because you have no way of referring to which element in the list your loop is pointing to. In the code above, the variable i is a temporary copy of each value in the list. Consequently, this doesn't work:

int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9};
for (int i: list)
    i = 0;  // Doesn't reset anything.  i is only a copy of each element.


On another hand, if your for-each loop iterates though an array of objects, then you can ask the objects to do anything you want. Here's an example:

ArrayList<String> list = new ArrayList<String>();

list.add("one");
list.add("two");
list.add("three");
...
list.add("nine");

for (String i: list)
    System.out.println(i.toUpperCase());  // No problem!


Be aware that although you may freely use each object in the Collection, you can't modify the contents of each object. Here's an example:

ArrayList<String> list = new ArrayList<String>();

list.add("one");
list.add("two");
list.add("three");
...
list.add("nine");

for (String i: list)
    i = i.toUpperCase());  // Doesn't affect list


The reason this doesn't work is because i is a reference variable pointing, turn by turn, to each element in list. If you try to change i, you will end up with a new object and new memory location for your i variable, not the original list variable that i was pointing to. If you think this is confusing, wait until you study 'pointers' in C-programming ;)

Last modified: December 12, 2022

Back to Arrays And Algorithms

Dark Mode

Outline