Practical No: 5
Title: Program on Collections (ArrayList/ Vectors)
Theory:
Vector class
Vector class is present in java.util package.
Vector class is used to create Generic Dynamic Array that can hold objects of any type and any number.
Vector is like the dynamic array which can grow or shrink its size.
Like array, an elements of can be accessed using an index.
Vector is synchronized.
Constructors of Vector class are as follows:
Vector( )
Vector(int capacity)
Vector(int capacity, int incr)
ArrayList class
ArrayList class is present in java.util package.
ArrayList is like the dynamic array which can grow or shrink its size.
ArrayList class is non synchronized.
ArrayList class maintains insertion order.
We can not create an array list of the primitive types, such as int, float, char, etc.
Constructors of ArrayList class are as follows:
ArrayList() Constructs an empty list with an initial capacity of ten.
ArrayList(int capacity) Constructs an empty list with the specified initial capacity.
Programs:
1. Program to accept students name from command line and store them in vector.
import java.util.Vector;
public class VectorDemo1
{
public static void main(String[] args)
{
Vector<String> v = new Vector<String>(); //creating vector for storing strings
for(int i=0;i<args.length;i++)
v.add(args[i]); //storing command line arguments in vector
System.out.println("Vector elements are: ");
for(int i=0;i<v.size();i++)
System.out.println(v.get(i)); //displaying vector elements
}
}
2. Program to demonstrate ArrayList class and its methods
import java.util.*;
public class ArrayListDemo
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>(5); //creating ArrayList for storing integers
list.add(10); //adding an integer in ArrayList
list.add(50);
list.add(70);
list.add(20);
System.out.println("ArrayList elements are: "+list);
System.out.println("Size of ArrayList is: "+list.size());
System.out.println("Element at 2nd index:"+list.get(2)); //displaying element which is at 2nd index
list.add(3,30); //adding an integer 30 at 3 index
System.out.println("After adding 30 at 2nd index: "+list);
list.remove((Integer)50); //removing an integer 50 from ArrayList
System.out.println("After removing element 50: "+list);
list.remove(2); //removing element which is at 2nd index
System.out.println("After removing element at 2nd index: "+list);
}
}