ArrayListExample.java import java.util.ArrayList;
import java.util.List;
public class ArrayListExample
{
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Ram");
list.add("Dave");
list.add("Peter");
list.add("John");
System.out.println(list);
}
}
Output [Ram, Dave, Peter, John]
ArrayListForEachExample.java import java.util.ArrayList;
import java.util.List;
public class ArrayListForEachExample
{
public static void main( String[] args )
{
List<String> list = new ArrayList<String>();
list.add("Ram");
list.add("Dave");
list.add("Peter");
list.add("John");
/*
* Using for-each loop getting each element from the list.
*/
for( String name : list )
{
System.out.println(name);
}
}
}
Ouput Ram
Dave
Peter
John
ArrayListForLoopIteratorExample.java import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListForLoopIteratorExample
{
public static void main( String[] args )
{
List<String> list = new ArrayList<String>();
list.add("Ram");
list.add("Dave");
list.add("Peter");
list.add("John");
/*
* Using Iterator to get each element from the list.
*/
for( Iterator<String> iterator = list.iterator(); iterator.hasNext(); )
{
String name = iterator.next();
System.out.println(name);
}
}
}
Output Ram
Dave
Peter
John
ArrayListWhileLoopIteratorExample.java import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListWhileLoopIteratorExample
{
public static void main( String[] args )
{
List<String> list = new ArrayList<String>();
list.add("Ram");
list.add("Dave");
list.add("Peter");
list.add("John");
Iterator<String> iterator = list.iterator();
/*
* Using Iterator to get each element from the list.
*/
while( iterator.hasNext() )
{
String name = iterator.next();
System.out.println(name);
}
}
}