© Doug Winnie 2021
D. WinnieEssential Java for AP CompScihttps://doi.org/10.1007/978-1-4842-6183-5_51

51. Using for…each Loops

Doug Winnie1  
(1)
Mission Hills, KS, USA
 

When you have a collection, you have a group of stuff. When you sort through those items and need to go through them, ultimately, it doesn’t matter how many there are, you still need to go through all of them.

You look at the pile of stuff, pick one up, do things with it, and then move on to the next item on the pile. Do you care which ordinal number it is? No. Do you care how many there are in total? Maybe, but you know that you just have to go through them all.

The for loop is a great type of loop for when you know precisely how many items you need to work with. Using the size() method of ArrayLists or the length property with arrays, you know how many you need to work with and can then numerically go through them all one by one.

But there is another way, and it is way simpler, and you don’t need to keep track of so many things at once.

Mechanics of a for…each Loop

The for...each loop is similar in name, but different in structure. Think of it this way. You have a pile of shirts that you need to fold. That pile is called laundry. When you need to fold a shirt, you find a shirt, and it is in your hand. It doesn’t matter which shirt in the laundry pile it is, but you know it’s a shirt, and you call it foldMe.

You do your thing, folding your shirt the way you fold all of your shirts, and then put it away. You then go back to the laundry pile and get another shirt, this time a different shirt, but you still call it foldMe, because you are going through all of the shirts, and as you loop through all of them, you need to give it some sort of name.

A for…each loop is similar to a for loop, but different in terms of how it works through a collection of objects. Think of it like a pile of laundry. With a for loop, that pile of laundry needs to be arranged, so each shirt, sock, and pair of pants is in a specific order. You then go to each one, one by one, and perform an action, like folding them, and then go through them all.

But when it comes to laundry, it doesn’t really matter what order you do them in. You just need to fold all the clothes. Arranging them into a specific order isn’t particularly valuable. That is the difference of a for…each loop. In the preceding example, the for…each loop looks at the pile of laundry. It doesn’t require that things be in a sequential order; it just picks up an item off the pile, and while it is in your hands, you can perform a specific task, like fold it, and then go back to the pile and grab another one. It does this until the pile is exhausted of items. In this case, it doesn’t matter which one is first or last.

This Is the Mechanics of the for…each Loop

If we have a collection of Strings , we can loop through them using a for...each loop. Let’s start with a new collection of names:
ArrayList<String> names = new ArrayList<String>();
names.add("Doug");
names.add("Mike");
This collection contains two names, both stored as Strings. We can then create our for...each loop to go through each item in the collection:
for (String name : names) {
    System.out.println(name);
}

When you look at this, read it this way: for each String in the collection names, perform these actions, referring to the current item as name.

Reading it this way, the section inside of the parentheses makes sense. You define the type of value you will be looping through in the collection. This is important so your program knows how to deal with different value types since integers, decimals, strings, and other types have different properties and methods. The colon is new and means that we are working with an item inside a collection. The colon defines which is the item and which is the collection. Item on the left, collection on the right.

Then, for the loop body, we refer to the item we are using from the collection by the name we defined at the top. In this case, by the identifier name.

We can then work with that object just like any other value of that value type, and if we change or update that value using the identifier, the change happens to the object in the collection, even after the loop is finished.

Often, you will work with data that has been formatted or analyzed before you use it in your program. One of the common ways to send and transmit information is using a delimited list.

In the preceding example, the program outputs each name on a different line.

ArrayLists Without Generics

One of the most flexible parts of ArrayLists is that they don’t have to be typed. Each collection can contain a variety of different types. So, with a for...each loop, how do you go through them?

We have to remember that an untyped ArrayList is still typed, but it is typed with the most basic item in Java: the Object class. Using the Object class type, we can loop through all the items in the collection:
ArrayList values = new ArrayList();
values.add(5);
values.add(3.14159);
values.add('a');
values.add("Hello!");
for (Object item : values) {
    System.out.println(item);
}

In this example, the collection values have all kinds of different types, but because we create our for...each loop using the Object type, we can still work with each one, but only as Object instances.

Yep, Arrays Work Too

Using the for...each loop doesn’t just stop with ArrayList collections, you can also use them with regular arrays. Just type the loop to the array type, and you can work with all the items using a more concise format:
int[] nums = new int[] {1,2,3,4,5,6};
for (int a : nums) {
    a *= a;
    System.out.println(a);
}

Again, the most flexible part of the for...each loop is that you don’t need to worry about how many items are in the collection or set, and you don’t need to work with each item by number, so if you are going through all of the items in a set, the for...each loop is a great option.

Code Examples

This code is also available on GitHub at the following location:

https://github.com/Apress/essential-java-AP-CompSci
import java.util.ArrayList;
public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<String>();
        names.add("Doug");
        names.add("Mike");
        for (String name : names) {
            System.out.println(name);
        }
        ArrayList values = new ArrayList();
        values.add(5);
        values.add(3.14159);
        values.add('a');
        values.add("Hello!");
        for (Object item : values) {
            System.out.println(item);
        }
        int[] nums = new int[] {1,2,3,4,5,6};
        for (int a : nums) {
            a *= a;
            System.out.println(a);
        }
    }
}
/* Output
Doug
Mike
5
3.14159
a
Hello!
1
4
9
16
25
36     
*/
Listing 51-1

Examples of the for…each loop

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.2.15