ArrayList Class



The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed. In Java, standard arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you may not know util run time precisely how large of an array you need. To handle this situation, the collections framework defines ArrayList.

In essence, an ArrayList is a variable-length array of object references. Thjat is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the arraya may be shrunk.

It is dynamically growing array that stores objects. It is not Synchronized and Vector is a Synchronized

Note: You can’t store primitive data type. we can store only object into ArrayList.

ArrayList has the constructors shown here:

–> ArrayList();  //This constructor builds an empty array list

–> ArrayList(Collection c)  // This constructor builds an array list that is initialized with the elements of collection c.

–> ArrayList(int capacity//This Contructor builds an array list that has the specified initial capacity.

1) To Creat  an ArrayList

ArrayList arl=new ArrayList();  //creating an object

ArrayList Arl=new ArrayList(20);  //creating an object with the size

2) To add objects use add() method

arl.add(“APPLE”);

arl.add(2,”APPLE”);

3) To Remove objects use remove().

arl.remove(“APPLE”);  //remove an string

arl.remove(2);  //removing the string  of specified location

4) To Know Number of objects, use size()

int n= arl.size()   // It displays the size of the array list.

Example of using an ArrayList.

//Demonstrating ArrayList.

import java.util.*;

class Arraylist Demo  {
public static void main(String args[])  {

ArrayList list=new ArrayList();  //creating an object for ArrayList class
System.out.println(“Initial size of al:”+al.size());

//add  elements to the array list
al.add(“C”);
al.add(“B”);
al.add(“A”);
al.add(“D”);
al.add(“E”);
al.add(“T”);
al.add(1,”A2″);

System.out.println(“Size of al after additions: “+ al.size());

//display the array list
System.out.println(“Content of al:”+al);

//Remove elements from the array list
al.remove(“F”);
al.remove(2);

System.out.println(“size of al after deletion:” +al.size());
System.out.println(“contents of al:”+al);
}
}

Share with SociBook.com

Related Post

  1. 2 Comment(s)

  2. By Subbu on Nov 3, 2008 | Reply

    Good post.. keep up the work..

  3. By aditya on Jan 16, 2012 | Reply

    Good.Need to do More Work On it and Spell Checks.

Post a Comment