Traversing an ArrayList
Get familiar with different traversal techniques for an ArrayList object.
We'll cover the following...
Just like we can use iteration statements to traverse arrays, we can apply them in the case of an ArrayList
too.
Traversal with the for
loop
Look at the program below.
Press + to interact
import java.util.ArrayList;class ArrayListTraversal{public static void main(String args[]){ArrayList<String> students = new ArrayList<String>(); // empty list// Adding elementsstudents.add("James");students.add("Allen");for(int i = 0; i < students.size(); i++) // Traversing ArrayList{System.out.println(students.get(i));}}}
Initially, we create an empty ArrayList
with the name: students
. Then, we add James and Allen to it. Now, look at line 13. We have a for
loop that traverses students.size()
...