import java.util.*;
class ArrayListDemo
{
public static void main(String args[])
{
// create an array list
ArrayList<String> al = new ArrayList<String>();
System.out.println("Initial size of al: " +
al.size());
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " +
al.size());
// display the array list
System.out.println("Contents of al: " + al);
// Remove elements from the array list
al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " +
al.size());
System.out.println("Contents of al: " + al);
//Iterator to display elements
System.out.print("Displaying contents of al using Iterator: ");
Iterator itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
//For each, alternative to iterator
System.out.print("Displaying contents of al using for each: ");
for(String s:al)
{
System.out.print(s + " ");
}
System.out.println();
// modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext())
{
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext())
{
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious())
{
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
Output:
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]
Displaying contents of al using Iterator: C A2 E B D
Displaying contents of al using for each: C A2 E B D
Modified contents of al: C+ A2+ E+ B+ D+
Modified list backwards: D+ B+ E+ A2+ C+
Note:
- ArrayList implements only List interface.
No comments:
Post a Comment