Example 1: Iterate through ArrayList using for loop
Output
ArrayList: [Java, JavaScript, Python] Iterating over ArrayList using for loop: Java, JavaScript, Python,
In the above example, we have created an arraylist named languages. Here, we have used the for loop to access each element of the arraylist.
Example 2: Iterate through ArrayList using for-each loop
Output
ArrayList: [Java, JavaScript, Python] Iterating over ArrayList using for-each loop: Java, JavaScript, Python,
Here, we have used the for-each loop to iterate over the ArrayList and print each element.
Example 3: Iterate over ArrayList using listIterator()
Output
ArrayList: [1, 3, 2] Iterating over ArrayList: 1, 3, 2,
In the above example, we have used the listIterator() method to iterate over the arraylist. Here,
- hasNext() - returns true if there is next element in the arraylist
- next() - returns the next element of the arraylist
Note: We can also use the ArrayList iterator() method and the ArrayList forEach() method to iterate over the arraylist.