Java. Extended for loop. General form. Examples. Processing arrays, collections of objects ArrayList, LinkedList

Extended for loop. General form. Examples. Processing arrays, collections of objects ArrayList, LinkedList


Contents



1. Purpose, general form and principle of the extended cycle for

In Java programs, it is often necessary to implement processing of arrays, collections, data sets. The most common operation in the processing of data arrays is the enumeration of each element of the array. To ensure iteration, one of the known loop operators is used (for, while, do … while). Most often, for iterating over the elements of an array, a for loop is used.

Since the enumeration of array elements is a standard operation, Java developers have introduced an additional format for the loop, which provides a more simplified, rational implementation. In this implementation, the general form of the for loop is similar to that of the foreach loop in other programming languages.

The general form of the extended for loop is as follows:

for (type variable : collection) {
    // some operators
    // ...
}

here

  • type – type of internal variable named variable;
  • variable – internal variable of type type that has visibility within the boundaries of the block of curly brackets { }. This variable is iterative. It stores the elements of the collection;
  • collection – a set of data that is iterated over in a loop. The data set can be a collection or an array.

The extended for loop works as follows. In the extended for loop, sequential enumeration of all elements of a collection or array occurs. The number of loop iterations is equal to the number of elements in the collection or array. At each iteration, the value of the array element is placed in an iterative variable named ‘variable’, which can be processed or used. The cycle guarantees the passage of the entire collection (array) from the first item to the last.

 

2. Examples of arrays processing with extended for loop

2.1. Example. Processing of an array of numbers of type int (primitive data type).

The example demonstrates the use of an extended for loop to process a one-dimensional integer array A. Implemented counting the number of pair numbers of the array.

// initialization of one-dimensional array A
int[] A = { 1, 8, 3, 6, 5, 10, 31 , 24, 10, 13, 2, 4 };
int k = 0; // number of pair numbers

// extended for loop
for (int d : A)
    if (d%2 == 0)
        k++;
// k = 7

 

2.2. Example. Processing an array of objects of type Book

Let the Book class is declared

// class Book
class Book {
    String title; // title of book
    String author; // author name
    float price; // price
    int year; // year edition
}

Using the extended for loop for an array of type Book can be, for example, the following:

// declaring a one-dimensional array of type Book
Book B[];

// allocate memory for an array of 4 references to the type Book
B = new Book[4];

// allocate memory for each item of the array of type Book
for (int i=0; i<B.length; i++)
    B[i] = new Book();

// fill the array with values
B[0].title = "Book-1";
B[0].author = "Author-1";
B[0].price = 205.78f;
B[0].year = 2008;

B[1].title = "Book-2";
B[1].author = "Author-2";
B[1].price = 99.00f;
B[1].year = 2010;

B[2].title = "Book-3";
B[2].author = "Author-3";
B[2].price = 0.99f;
B[2].year = 2011;

B[3].title = "Book-4";
B[3].author = "Author-4";
B[3].price = 100.01f;
B[3].year = 2012;

// extended for loop
// search for books of 2011, 2012
for (Book book : B)
    if ((book.year==2011)||(book.year==2012))

System.out.println("Book: " + book.title + ", " + book.author);

As a result of executing the above code, the lines will be displayed

Book: Book-3, Author-3
Book: Book-4, Author-4

 

3. Examples of processing collections with an extended for loop

3.1. Example. Processing Integer type collection using ArrayList dynamic array

The example demonstrates how to handle a collection of integers using the ArrayList and Integer classes.

The ArrayList class implements a dynamic array, which can increas or decreas as needed. To use this class, you need to connect the java.util package. The ArrayList class declaration is as follows:

class ArrayList<E>

here

  • E – the type of objects that are stored in the array.

The class Integer is a wrapper class of type int, which represents integer values. In this example, the ArrayList class for processing objects of type Integer is as follows:

class ArrayList<Integer>

A demonstration of using an extended for loop for a collection of integers using the ArrayList class can be as follows

// include java.util package
import java.util.*;

...

// class ArrayList, object of type collection Integer

// Integer - class wrapper for int type
ArrayList<Integer> A = new ArrayList<Integer>(); // create a collection

// add items to the collection
A.add(5);
A.add(9);
A.add(-20);
A.add(11);
A.add(7); // A = { 5, 9, -20, 11, 7 }

// find the sum of the items of the collection
int sum = 0;
    for (Integer i : A) // extended for loop
        sum += i;

System.out.println("Sum = " + sum); // Sum = 12

 

3.2. Processing a collection of type Book using a linked list of LinkedList

Let the class (type) Book has the following declaration:

// class Book
class Book {
    String title; // title of book
    String author; // author name
    float price; // price
    int year; // year of issue
}

In this example, the LinkedList class is used to demonstrate the extended for loop. This class is designed to organize data of a given type into a linked list. To use the LinkedList class in the program, you need to include the java.util package. The class declaration is as follows:

class LinkedList<E>

here

  • E – type of objects that are saved in the list. In our case, this type is the class Book.

The program code that forms the book list of type Book and processes it in an extended for loop has the form:

// include java.util package

import java.util.*;

...

// declare and create an object of type LinkedList<Book>
LinkedList<Book> LB = new LinkedList<Book>();
Book B = new Book(); // additional variable

// create a list of LinkedList<Book> objects

// form an object of type Book
B.title = "Title-1";
B.author = "Author-1";
B.price = 10.00f;
B.year = 2000;

// add object B to the list
LB.add(B);

// add second object
B = new Book(); // re-allocate memory
B.title = "Title-2";
B.author = "Author-2";
B.price = 20.00f;
B.year = 2001;
LB.add(B);

// add third object
B = new Book(); // re-allocate memory
B.title = "Title-3";
B.author = "Author-3";
B.price = 30.00f;
B.year = 2002;
LB.add(B);

// display a LB list
int i=0;
for (Book B2 : LB) {
    i++;
    System.out.println("Book - " + i + ": " + B2.title + ", " + B2.author);
}

System.out.println("-----------------------------------");

// display the books 2001 release
for (Book B2 : LB)
    if (B2.year == 2001)
        System.out.println(B2.title + ", " + B2.author + ", " + B2.year);

In the above code in rows

int i=0;
for (Book B2 : LB) {
    i++;
    System.out.println("Book - " + i + ": " + B2.title + ", " + B2.author);
}

The position number in the linked Book list is calculated by introducing the additional variable i. There are cases when it is necessary to process not all elements of a collection. According to the value of the iterator i, you can determine the position number of the collection object that can be processed.

After executing the above code, the following will be displayed:

Book - 1: Title-1, Author-1
Book - 2: Title-2, Author-2
Book - 3: Title-3, Author-3
-----------------------------------
Title-2, Author-2, 2001

 

4. What are the advantages and disadvantages of using an extended for loop for arrays?

An extended for loop is convenient for handling collections. Using the extended for loop provides the following benefits:

  • simplicity and rationality of presentation in comparison with the for loop;
  • you do not need to use an additional loop variable, set its initial value and the condition for completing the loop;
  • no need to index the array.

The main disadvantage of the extended for loop is:

  • lack of “flexibility” in operating the iteration variable in cases when it is necessary to iterate over not all elements of the collection. For example, if you need to iterate only the first n items of the entire collection or the items that are placed in certain positions (pair positions, odd positions) in the collection. However, this disadvantage can be circumvented by introducing additional iterator variables and condition checking.

 


Related topics