21 Sept 2012

ArrayList in java with example

ArrayList class provides methods for basic array operations:
add( Object o ) - puts reference to object into ArrayList
get( int index ) - retrieves object reference from ArrayList index position
size() - returns ArrayList size
remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
clear() - removes all of the elements

In this example we are going to show the use of java.util.ArrayList. We will be creatiing an object of ArrayList class and performs various operations like adding removing the objects.

import java.util.*;
public class ArrayListDemo
{
  public static void main(String[] args)
 {
  ArrayList<Object> arl=new ArrayList<Object>();
  Integer i1=new Integer(10);
  Integer i2=new Integer(20);
  Integer i3=new Integer(30);
  Integer i4=new Integer(40);
  String s1="Sathya";
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.add(i1);
  arl.add(i2);
  arl.add(s1);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.add(i1);
  arl.add(i2);
  arl.add(i3);
  arl.add(i4);
  Integer i5=new Integer(50);
  arl.add(i5);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  arl.remove(3);
  Object a=arl.clone();
  System.out.println("The clone is: " + a);
  System.out.println("The content of arraylist is: " + arl);
  System.out.println("The size of an arraylist is: " + arl.size());
  }
}
 
Output:
The content of arraylist is: []
The size of an arraylist is: 0
The content of arraylist is: [10, 20, Sathya]
The size of an arraylist is: 3
The content of arraylist is: [10, 20, Sathya, 10, 20, 30, 40, 50]
The size of an arraylist is: 8
The clone is: [10, 20, Sathya, 20, 30, 40, 50]
The content of arraylist is: [10, 20, Sathya, 20, 30, 40, 50]
The size of an arraylist is: 7

0 comments:

Post a Comment