ArrayList is a resizable array used whenever we don’t know the size of the array. This can happen when we are creating an array or when we need a flexible size array.
We want to learn two different ways to print ArrayList elements in this shot.
Let’s first create a list that will be used to print elements:
import java.util.ArrayList;public class CustomerList {public static void main(String[] args) {ArrayList<String> clients = new ArrayList<String>();clients.add("Patience Kavira");clients.add("Sarah LIFAEFI");clients.add("Yves Madika");clients.add("Valentin Nasibu");clients.add("Jean Pierre Badibanga");clients.add("Delory Kondo");}}
for
loopWe first need to know the list’s length. We use the size()
method or ArrayList
for this.
Next, we have to fetch each element in the list. For this, the ArrayList
get()
method comes to the rescue.
Here’s the implementation of the loop:
for (int i = 0; i < clients.size(); i++) {
System.out.println(clients.get(i));
}
Let’s execute it:
import java.util.ArrayList;public class CustomerList {public static void main(String[] args) {ArrayList<String> clients = new ArrayList<String>();// Add clients names to the listclients.add("Patience Kavira");clients.add("Sarah LIFAEFI");clients.add("Yves Madika");clients.add("Valentin Nasibu");clients.add("Jean Pierre Badibanga");clients.add("Delory Kondo");// Print clients names using for loopSystem.out.println("List of clients: ");for (int i = 0; i < clients.size(); i++)System.out.println(clients.get(i));}}
for-each
loopIf we have nothing to do with indices, the for-each
loop might be the appropriate loop method to use. Here’s how it works:
for (String client : clients) {
System.out.println(client);
}
Let’s execute the for-each loop below:
import java.util.ArrayList;public class CustomerList {public static void main(String[] args) {ArrayList<String> clients = new ArrayList<String>();// Add clients names to the listclients.add("Patience Kavira");clients.add("Sarah LIFAEFI");clients.add("Yves Madika");clients.add("Valentin Nasibu");clients.add("Jean Pierre Badibanga");clients.add("Delory Kondo");// Print clients names using for-each loopSystem.out.println("List of clients: ");for (String client : clients)System.out.println(client);}}
That’s all for this shot. We have learned to print ArrayList
items using the for
and for-each
loops.