Wednesday, 30 November 2016

Program to demonstrate use of ArrayList class

Arraylist is a class which implements List interface. It is widely used because of the functionality and flexibility it offers. Java ArrayList class uses a dynamic array for storing the elements.

The issue with arrays is that they are of fixed length so if it is full we cannot add any more elements to it, likewise if there are number of elements gets removed from it the memory consumption would be the same as it doesn’t shrink. On the other ArrayList can dynamically grow and shrink as per the need. Apart from these benefits ArrayList class enables us to use predefined methods of it which makes our task easy.

This program shows some of the methods of ArrayList class. I'm going to add String elements so I made it of string type as given below:
ArrayList<String>  al  =  new ArrayList<String>( );


Few of the important methods of ArrayList are given below:
  1. add( Object o) : Adds an object to the arraylist.
  2. add(int index, Object o) : Adds the object to the arraylist at the given index.
  3. remove(Object o) : Removes the object o from the ArrayList.
  4. remove(int index) : Removes the element from a given index.
  5. Object get(int index) : Returns the object of list which is present at the specified index.
  6. int size( ) : Gives the size (number of elements) of the ArrayList.
  7. boolean contains(Object o) : Checks whether the given object o is present in the array list if its there then it returns true else it returns false.
  8. clear( ) : Used for removing all the elements of the array list


PROGRAM
//Demonstrate ArrayList.
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("After deleting elements al contains=> ");
  
  for(int i=0; i<al.size(); i++) {
   System.out.print("   " + al.get(i) );
  }
 }
}
OUTPUT
C:\>javac ArrayListDemo.java
C:\>java ArrayListDemo
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
After deleting elements al contains=> 
   C   A2   E   B   D

No comments:

Post a Comment