ArrayList<String> namesList = new ArrayList<String>(Arrays.asList( "alex", "brian", "charles") );
for(String name : namesList)
{
System.out.println(name);
}
// will iterate through each index of the array list
// using the size of the array list as the max.
// (the last index is the size of the array list - 1)
for (int i = 0; i < myArrayList.size(); i++) {
System.out.println(myArrayList.get(i));
// will print each index as it loops
}
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
// add elements in the arraylist
animals.add("Peacock");
animals.add("Markhor");
animals.add("Cow");
System.out.println("ArrayList: " + animals +"
");
// iterate using for-each loop
System.out.println("Accessing individual elements:
");
for (String language : animals) {
System.out.print(language);
System.out.print("
");
}
}
}