Collections

how to use ArrayList of Collections in java
Previous Home Next

 

In the following example we will see how can we create an ArrayList and perform various insertion and deletion operations in the created  ArrayList.

In this example we have created a class CollectionExample which creates and manipulates an ArrayList.
 In this example we have used the main() method which contains the various operations that creates an ArrayList.

In this example we have created a class Collection Example having a main() method. In this class we have created an ArrayList named al in which elements are added using add() method of the ArrayList and elements are removed by using the remove() method of the ArrayList.

 
package r4r.co.in;
import java.util.ArrayList;
import java.util.Iterator;


public class CollectionExample {

/**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub

ArrayList<String> al=new ArrayList<String>(); // creating an ArrayList named al
al.add("r4r"); // adding string objects to the arraylist
al.add("development");
al.add("tutorials");
al.add("shashi");
al.add("s/w engineer");
System.out.println("The size of the arraylist is: "+al.size()); // determining the length of the arraylist
System.out.println("The contents of the list are :"+al); // showing the contents of the arraylist
Iterator<String> itr=al.iterator(); // Invoking the Iterator on the arraylist al

itr.next(); // passing over the first element
itr.remove(); // removing the first element
System.out.println("The elements in the ArrayList after the deletion are as follows: ");
while(itr.hasNext()) // iterating over the list
{
System.out.println(itr.next()); // printing the remaining elements in the list
}
}

}
The output of the above program is as follows:

The size of the arraylist is: 5
The contents of the list are :[r4r, development, tutorials, shashi, s/w engineer]
The elements in the ArrayList after the deletion are as follows:
development
tutorials
shashi
s/w engineer

Previous Home Next