Tuesday, 7 April 2015

Filled Under:

Tutorial On Array List In Java

The array list extends Abstract list and implements the list interface the speciality of array list is that it can be grown or shrink any time in the program it has no fixe size as array have its constructor are shown below
ArrayList()
ArrayList(int capacity)

The first method is used in program while second one is used to set initial capacity of array list.

DIFFERENCE BETWEEN ARRAY AND ARRAY LIST:

Arrays have fixed length and once they have created their size cannot be increased or decreased on the other side the size of array list can be increased or decreased during program at any time as we have done in below program.Array list also has a unique capacity it is the size of array that can store elements in a list as element is increases its capacity is also increases.Array list have add or remove methods but array does not have any such type of methods 
following are the common methods of array list.

METHODS OF ARRAY LIST:

void add(int index,Object)

By using this method user can specify the specific position of object in an array list.

boolean add(object ob)

This method add the element in the last position of an array list.

boolean addAll(Collection c)

By using this method user can add all elements of  specified collection into a last position of array list.

boolean addAll(int index,Collection c)

This method is also used to add collection in array list but its add collection at specified position.

Void clear()

This method is applicable  when user want's to clear all elements of arraylist.

Object get(int index)

This method can be used when user wants to get data from specific index in array list.

int indexOf(Object ob)

This method returns the  index of specified object.

Object remove(int index)

This method remove the object at the specified position in an array list.

Object set(int index, Object element)

This method is very useful when user want's to replace the specified object with a new one at a specified  position.

int size()

This method is used to check the size of specified array list.


CODING:

import java.util.*;
class arrlist
{
public static void main(String args[])
{
ArrayList a1 = new ArrayList();
System.out.println("Initial size of a1:"+a1.size());
a1.add("J");
a1.add("A");
a1.add("V");
a1.add(3,"A");
System.out.println("Size of a1 after addition:"+a1.size());
System.out.println("contents of a1 after addition:"+a1);
a1.remove("J");
a1.remove(0);
System.out.println("Size of a1 after deleting:"+a1.size());
System.out.println("contents of a1 after deleting:"+a1);

}
}

OUTPUT:





0 comments:

Post a Comment