Java Program to demonstrate ArrayList
Program
package ALDemo;
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList aList = new ArrayList();
aList.add(11);
aList.add(0, 21);
aList.add(aList.size(), 31);
aList.add(41);
System.out.println(aList);
Collections.sort(aList);
Collections.reverse(aList);
System.out.println("Traverse using get() method:");
for(int i = 0; i < aList.size(); i++)
System.out.println(aList.get(i));
System.out.println("Traverse by iterator interface:");
Iterator itr = aList.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
System.out.println("Traverse by ListIterator interface forward direction:");
ListIterator litr = aList.listIterator();
while(litr.hasNext())
System.out.println(litr.next());
System.out.println("Traverse by ListInterator interface backward direction:");
while(litr.hasPrevious())
System.out.println(litr.previous());
aList.removeAll(aList);
System.out.println("After removing all the items from the list:");
System.out.println(aList);
}
}
Output
$ javac -d . ArrayListDemo.java
$ java ALDemo.ArrayListDemo
[21, 11, 31, 41]
Traverse using get() method:
41
31
21
11
Traverse by iterator interface:
41
31
21
11
Traverse by ListIterator interface forward direction:
41
31
21
11
Traverse by ListInterator interface backward direction:
11
21
31
41
After removing all the items from the list:
[]