Member-only story
Hi everyone, welcome back. In these examples, we will be going over how to loop through arraylists in Java. Arraylists can be used to store a collection of data, similar to that of an arraylist. The key difference between an arraylist and an array is that an arraylist is resizable whereas an array is not. This leaves the arraylist as a great choice when wanting to modify a collection of data. With this introduction out of the way, let’s get into it.
Creating And Populating ArrayList
Let’s start by creating and populating our arraylist. Before we can create the arraylist, we need to make sure we have our arraylist import, which is included within the java.util package:
import java.util.ArrayList;
Now, we can create and populate our arraylist:
ArrayList<String> myArrList = new ArrayList<String>();
myArrList.add("One");
myArrList.add("Two");
myArrList.add("Three");
System.out.println(myArrList);Output:
[One, Two, Three]
We have now successfully created and populated our arraylist.
Looping Through ArrayLists
Now, let’s see how we can loop through an arraylist. We can use a for-each loop to print each…