In this example you will learn you to iterate a generic collection using the for-each
loop. There was actually no for-each
keyword or statement in Java. It just a special syntax of the for
loop. The structure or syntax of the for-each
loop is as follows.
for (type var : collections) {
body;
}
This form of for
loop is always read as foreach
and the colon (:) character is read as “in”. Given that definition, if the type is a String you will read the syntax above as “foreach String var in collections”. The var in the statement above will be given each value from the collections during the iteration process.
Let’s compare two codes, the first one that use a generic and another code that does not use a generic so we can see the difference from the iteration perspective when working with a collection.
package org.kodejava.generics;
import org.kodejava.generics.support.Customer;
import java.util.ArrayList;
import java.util.List;
public class ForEachGeneric {
public void loopWithoutGeneric() {
List customers = new ArrayList();
customers.add(new Customer());
customers.add(new Customer());
customers.add(new Customer());
for (int i = 0; i < customers.size(); i++) {
Customer customer = (Customer) customers.get(i);
System.out.println(customer.getFirstName());
}
}
public void loopWithGeneric() {
List<Customer> customers = new ArrayList<>();
customers.add(new Customer());
customers.add(new Customer());
customers.add(new Customer());
for (Customer customer : customers) {
System.out.println(customer.getFirstName());
}
}
}
What you see from the code snippet above is how much more clean our code is when we are using the generic version of the collection. In the first method, the loopWithoutGeneric
we have to manually cast the object back to the Customer
type. But in the second method, the loopWithGeneric
method, no cast is needed as the collection will return the same type as what the collection was declared to hold.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024