Unit-Iii Collection Framework
Unit-Iii Collection Framework
UNIT-III
COLLECTION FRAMEWORK
Let us see the hierarchy of collection framework.The java.util package contains all
the classes and interfaces for Collection framework.
2
JCF Interfaces:The classes in the JCF are all found in the java.util package. Three
important interfaces from this group are: List;Set;Map.
Increased Quality – Using core collection classes that are well tested increases
our program quality rather than using any home developed data structure.
Reusability and Interoperability
Collection Interface: This interface will implemented by all the classes in the
collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as
follows:
Iterator interface
There are only three methods in the Iterator interface. They are:
ArrayList Class
5
The size, isEmpty, get, set, iterator, and listIterator operations run in constant time.
The add operation runs in amortized constant time, that is, adding n elements
requires O(n) time. All of the other operations run in linear time (roughly
speaking). The constant factor is low compared to that for the LinkedList
implementation.
o Java ArrayList class uses a dynamic array for storing the elements.It extends
AbstractList class and implements List interface.
o Java ArrayList class can contain duplicate elements.
o Java ArrayList class maintains insertion order.
o Java ArrayList class is non synchronized.
o Java ArrayList allows random access because array works at the index basis.
Syntax of creatingArrayList:
In generic collection, we specify the type in angular braces. Now ArrayList is forced
to have only specified type of objects in it. If you try to add another type of
object, it gives compile time error.
import java.util.*;
6
class TestCollection1{
public static void main(String args[])
{
ArrayList<String> al=new ArrayList<String>();//creating arraylist
al.add("Ravi");//adding object in arraylist
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator itr=al.iterator();//getting Iterator from arraylist to traverse elements
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Hashtable class
o A Hashtable is an array of list.Each list is known as a bucket.The position of
bucket is identified by calling the hashcode() method.A Hashtable contains
values based on the key. It implements the Map interface and extends
Dictionary class.
o It contains only unique elements.
o It may have not have any null key or value.
o It is synchronized.
7
Example of Hashtable:
import java.util.*;
class TestCollection16{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
Output:103 Rahul
102 Ravi
101 Vijay
100 Amit
Vector Class:
The Vector class implements a growable array of objects. Like an array, it contains
components that can be accessed using an integer index. However, the size of
a Vector can grow or shrink as needed to accommodate adding and removing
items after the Vector has been created.
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections
framework.
Vector proves to be very useful if you don't know the size of the array in advance
or you just need one that can change sizes over the lifetime of a program.
The Vector class supports four constructors. The first form creates a default vector,
which has an initial size of 10:
Vector( )
The second form creates a vector whose initial capacity is specified by size:
Vector(int size)
The third form creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward:
The fourth form creates a vector that contains the elements of collection c:
Vector(Collection c)
9
Example Program:
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
10
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
Output:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
11
Stack:
Stack only defines the default constructor, which creates an empty stack. Stack
includes all the methods defined by Vector, and adds several of its own.
Stack( )
Apart from the methods inherited from its parent class Vector, Stack defines
following methods:
boolean empty()
1 Tests if this stack is empty. Returns true if the stack is empty,
and returns false if the stack contains elements.
Object peek( )
2 Returns the element on the top of the stack, but does not
remove it.
Object pop( )
3 Returns the element on the top of the stack, removing it in the
process.
Example:
import java.util.*;
showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}
stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
14
The Enumeration:
This interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects.
boolean hasMoreElements( )
When implemented, it must return true while there are still
1
more elements to extract, and false when all the elements have
been enumerated.
Object nextElement( )
2 This returns the next object in the enumeration as a generic
Object reference.
Example:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
15
Enumeration days;
Vector dayNames = new Vector();
dayNames.add("Sunday");
dayNames.add("Monday");
dayNames.add("Tuesday");
dayNames.add("Wednesday");
dayNames.add("Thursday");
dayNames.add("Friday");
dayNames.add("Saturday");
days = dayNames.elements();
while (days.hasMoreElements()){
System.out.println(days.nextElement());
}
}
}
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday