0% found this document useful (0 votes)
25 views

Unit-Iii Collection Framework

The document discusses the Java Collection Framework. It describes the hierarchy and interfaces like List, Set and Map. Benefits of using JCF are reduced effort, increased quality and reusability. Core Collection interface and its methods are explained. Iterator interface and its methods are also described. Classes like ArrayList, Hashtable and Vector are explained with examples.

Uploaded by

elrick171
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Unit-Iii Collection Framework

The document discusses the Java Collection Framework. It describes the hierarchy and interfaces like List, Set and Map. Benefits of using JCF are reduced effort, increased quality and reusability. Core Collection interface and its methods are explained. Iterator interface and its methods are also described. Classes like ArrayList, Hashtable and Vector are explained with examples.

Uploaded by

elrick171
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

1

UNIT-III

COLLECTION FRAMEWORK

• A Collection is a container that groups similar elements into an entity.

• Examples would include a list of bank accounts, set of students, group of


telephone numbers.

• The Collections framework in Java offers a unified approach to store, retrieve


and manipulate a group of data

• Java’s Collection framework has an intuitive approach when compared to


other complex frameworks such as C++ .

Hierarchy of 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.

Benefits of Java Collections Framework:

 Reduced Development Effort – It comes with almost all common types of


collections and useful methods to iterate and manipulate the data. So we can
concentrate more on business logic rather than designing our collection APIs.

 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:

No. Method Description

1 public boolean add(Object is used to insert an element in this


element) collection.

2 public boolean is used to insert the specified


addAll(collection c) collection elements in the invoking
collection.

3 public boolean is used to delete an element from


3

remove(Object element) this collection.

4 public boolean is used to delete all the elements


removeAll(Collection c) of specified collection from the
invoking collection.

5 public boolean is used to delete all the elements


retainAll(Collection c) of invoking collection except the
specified collection.

6 public int size() return the total number of


elements in the collection.

7 public void clear() removes the total no of element


from the collection.

8 public boolean is used to search an element.


contains(object element)

9 public boolean is used to search the specified


containsAll(Collection c) collection in this collection.

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.


4

13 public boolean matches two collection.


equals(Object element)

14 public int hashCode() returns the hashcode number for


collection.

Iterator interface

Iterator interface provides the facility of iterating the elements in forward


direction only.

Iterator interface provides methods to iterate over any Collection. We can


get iterator instance from a Collection using iterator method. Iterator takes
the place of Enumerationin the Java Collections Framework. Iterators allow
the caller to remove elements from the underlying collection during the
iteration. Iterators in collection classes implementIterator Design Pattern.

Methods of Iterator interface:

There are only three methods in the Iterator interface. They are:

1. public boolean hasNext() it returns true if iterator has more elements.


2. public object next() it returns the element and moves the cursor pointer
to the next element.
3. public void remove() it removes the last elements returned by the
iterator. It is rarely used.

ArrayList Class
5

Resizable-array implementation of the List interface. Implements all optional list


operations, and permits all elements, including null. In addition to implementing
the List interface, this class provides methods to manipulate the size of the array
that is used internally to store the list. (This class is roughly equivalent to Vector,
except that it is unsynchronized.)

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:

ArrayList<String> al=new ArrayList<String>();//creating new generic arraylist

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.

Example of Java ArrayList class

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.

Each vector tries to optimize storage management by maintaining a capacity and


a capacityIncrement. The capacity is always at least as large as the vector size; it is
usually larger because as components are added to the vector, the vector's storage
8

increases in chunks the size of capacityIncrement. An application can increase the


capacity of a vector before inserting a large number of components; this reduces
the amount of incremental reallocation.

Vector implements a dynamic array. It is similar to ArrayList, but with two


differences:

 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:

Vector(int size, int incr)

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 is a subclass of Vector that implements a standard last-in, first-out 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:

SN Methods with Description

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.

Object push(Object element)


4
Pushes element onto the stack. element is also returned.

int search(Object element)


5
Searches for element in the stack. If found, its offset from the
12

top of the stack is returned. Otherwise, .1 is returned.

Example:

The following program illustrates several of the methods supported by this


collection:

import java.util.*;

public class StackDemo {

static void showpush(Stack st, int a) {


st.push(new Integer(a));
System.out.println("push(" + a + ")");
System.out.println("stack: " + st);
}

static void showpop(Stack st) {


System.out.print("pop -> ");
Integer a = (Integer) st.pop();
System.out.println(a);
System.out.println("stack: " + st);
}

public static void main(String args[]) {


Stack st = new Stack();
System.out.println("stack: " + st);
showpush(st, 42);
13

showpush(st, 66);
showpush(st, 99);
showpop(st);
showpop(st);
showpop(st);
try {
showpop(st);
} catch (EmptyStackException e) {
System.out.println("empty stack");
}
}
}

This would produce the following result:

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

pop -> empty stack

The Enumeration:

This interface defines the methods by which you can enumerate (obtain one at a
time) the elements in a collection of objects.

This legacy interface has been superceded by Iterator. However, it is used by


several methods defined by the legacy classes such as Vector and Properties, is used
by several other API classes, and is currently in widespread use in application code.

The methods declared by Enumeration are summarized in the following table:

SN Methods with Description

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:

Following is the example showing usage of Enumeration.

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());
}
}
}

This would produce the following result:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

You might also like