Java Collection Framework
Java Collection Framework
Java Collection Framework
UNIT-III
The Collection Framework
In order to handle group of objects we can use array of objects If we have a class called
Employ with members name and id, if we want to store details of 10 Employees, create an
array of object to hold 10 Employ details
Employ ob [] = new Employ [10];
We cannot store different class objects into same array
Inserting element at the end of array is easy but at the middle is difficult
After retriving the elements from the array, in order to process the elements we dont have
any methods
Collection Object:
A collection object is an object which can store group of other objects
A collection object has a class called Collection class or Container class
All the collection classes are available in the package called 'javautil‟ (util stands for utility)
Group of collection classes is called a Collection Framework
A collection object does not store the physical copies of other objects; it stores references of
other objects
All the collection classes in javautil package are the implementation classes of different
interfaces
Set: A Set represents a group of elements (objects) arranged just like an array The set will
grow dynamically when the elements are stored into it A set will not allow duplicate
elements
List: Lists are like sets but allow duplicate values to be stored
Queue: A Queue represents arrangement of elements in FIFO (First In First Out) order This
means that an element that is stored as a first element into the queue will be removed first
from the queue
Map: Maps store elements in the form of key value pairs If the key is provided its
corresponding value can be obtained
Retrieving Elements from Collections: Following are the ways to retrieve any element from
a collection object:
74
Iterator Interface: Iterator is an interface that contains methods to retrieve the elements one
by one from a collection object It retrieves elementsonly in forward direction It has 3
methods:
Method Description
boolean hasNext() This method returns true if the iterator has more elements
element next() This method returns the next element in the iterator
void remove() This method removes the last element from the collection
returned by the iterator
Enumeration Interface: This interface is useful to retrieve elements one by one like Iterator
It has 2 methods
Method Description
boolean hasMoreElements() This method tests Enumeration has any more elements
element nextElement() This returns the next element that is available in Enumeration
HashSet Class: HashSet represents a set of elements (objects) It does not guarantee the order
of elements Also it does not allow the duplicate elements to be stored
· We can write the HashSet class as: class HashSet<T>
· We can create the object as: HashSet<String> hs = new HashSet<String> ();
HashSet();
HashSet (int capacity); Here capacity represents how many elements can be stored into th
HashSet initially This capacity may
: increase automatically when more
number of elements is being stored
Description
boolean add(obj) This method adds an element obj to the HashSet It returns true if the
element is added to the HashSet, else it returns false If the same
75
Program 1: Write a program which shows the use of HashSet and Iterator
//HashSet Demo
import javautil*;
class HS
{public static void main(String args[])
{//create a HashSet to store Strings
HashSet <String> hs = new HashSet<String> ();
//Store some String elements
hsadd ("India");
hsadd ("America");
hsadd ("Japan");
hsadd ("China");
hsadd ("America");
//view the HashSet
Systemoutprintln ("HashSet = " + hs);
//add an Iterator to hs
Iterator it = hsiterator ();
//display element by element using Iterator
Systemoutprintln ("Elements Using Iterator: ");
while (ithasNext() )
{String s = (String) itnext ();
Systemoutprintln(s);
}
}
}
Output:
76
LinkedHashSet Class: This is a subclass of HashSet class and does not contain any additional
members on its own LinkedHashSet internally uses a linked list to store the elements It is a
generic class that has the declaration:
class LinkedHashSet<T>
Stack Class: A stack represents a group of elements stored in LIFO (Last In First Out) order
This means that the element which is stored as a last element into the stack will be the first
element to be removed from the stack Inserting the elements (Objects) into the stack is called
push operation and removing the elements from stack is called pop operation Searching for an
element in stack is called peep operation Insertion and deletion of elements take place only
from one side of the stack, called top of the stack We can write a Stack class as:
class Stack<E>
eg: Stack<Integer> obj = new Stack<Integer> ();
Stack Class Methods:
Method Description
boolean empty() this method tests whether the stack is empty or not If the stack is
empty then true is returned otherwise false
element peek() this method returns the top most object from the stack without
removing it
this method pops the top-most element from the stack and returns
element pop() it
element push(element obj) this method pushes an element obj onto the top of the stack and
returns that element
int search(Object obj) This method returns the position of an element obj from the top of
the stack If the element (object) is not found in the stack then it
returns -1
Output:
LinkedList Class: A linked list contains a group of elements in the form of nodes Each node
will have three fields- the data field contatins data and the link fields contain references to
previous and next nodesA linked list is written in the form of:
class LinkedList<E>
we can create an empty linked list for storing String type elements (objects) as:
LinkedList <String> ll = new LinkedList<String> ();
LinkedList Class methods:
Method Description
boolean add (element obj) This method adds an element to the linked list It returns true if the
element is added successfully
This method inserts an element obj into the linked list at a
void add(int position, specified
element obj) position
void addFirst(element obj) This method adds the element obj at the first position of the linked
list
void addLast(element obj) This method adds the element obj at the last position of the linked
list
element removeFirst () This method removes the first element from the linked list and
returns it
element removeLast () This method removes the last element from the linked list and
returns it
element remove (int This method removes an element at the specified position in the
position) linked list
void clear () This method removes all the elements from the linked list
element get (int position) This method returns the element at the specified position in the
linked list
element getFirst () This method returns the first element from the list
element getLast () This method returns the last element from the list
This method replaces the element at the specified position in the
element set(int position, list
element obj) with the specified element obj
int size () Returns number of elements in the linked list
int indexOf (Object obj) This method returns the index of the first occurrence of the
specified element in the list, or -1 if the list does not contain the
element
This method returns the index of the last occurrence of the
int lastIndexOf (Object specified
obj) element in the list, or -1 if the list does not contain the element
.
78
Object[] toArray() This method converts the linked list into an array of Object class
type All the elements of the linked list will be stored into the array
in the same sequence
Note: In case of LinkedList counting starts from 0 and we start counting from 1
ArrayList Class: An ArrayList is like an array, which can grow in memory dynamically
ArrayList is not synchronized This means that when more than one thread acts simultaneously
on the ArrayList object, the results may be incorrect in some cases
ArrayList class can be written as: class ArrayList <E>
We can create an object to ArrayList as: ArrayList <String> arl = new ArrayList<String> ();
ArrayList Class
Methods:
Method Description
boolean add (element obj) This method appends the specified element to the end of the
ArrayList If the element is added successfully then the method
returns true
void add(int position, This method inserts the specified element at the specified positioin
. .
Vector Class: Similar to ArrayList, but Vector is synchronized It means even if several
threads act on Vector object simultaneously, the results will be reliable
Vector class can be written as: class Vector <E>
We can create an object to Vector
as: Vector <String> v = new Vector<String> ();
Vector Class Methods:
Method Description
This method appends the specified element to the end of the
boolean add(element obj) Vector
If the element is added successfully then the method returns true
void add (int position, This method inserts the specified element at the specified positioin
element obj) in the Vector
element remove (int This method removes the element at the specified position in the
position) Vector and returns it
boolean remove (Object This method removes the first occurrence of the specified element
obj) obj from the Vector, if it is present
void clear () This method removes all the elements from the Vector
element set (int position, This method replaces an element at the specified position in the
element obj) Vector with the specified element obj
boolean contains (Object This method returns true if the Vector contains the specified
obj) element obj
element get (int position) This method returns the element available at the specified position
in the Vector
int size () Returns number of elements in the Vector
int indexOf (Object obj) This method returns the index of the first occurrence of the
specified element in the Vector, or -1 if the Vector does not
contain
the element
This method returns the index of the last occurrence of the
int lastIndexOf (Object specified
obj) element in the Vector, or -1 if the Vector does not contain the
element
Object[] toArray ( ) This method converts the Vector into an array of Object class type
All the elements of the Vector will be stored into the array in the
same sequence
int capacity () This method returns the current capacity of the Vector
HashMap Class: HashMap is a collection that stores elements in the form of key-value pairs
If key is provided later its corresponding value can be easily retrieved from the HAshMap
Keys should be unique HashMap is not synchronized and hence while using multiple threads
on HashMap object, we get unreliable results
We can write HashMap class as: class HashMap<K, V>
For example to store a String as key and an integer object as its value, we can create the
HashMap as: HashMap<String, Integer> hm = new HashMap<String, Integer> ();
The default initial capacity of this HashMap will be taken as 16 and the load factor as 075
Load factor represents at what level the HashMap capacity should be doubled For example,
the product of capacity and load factor = 16 * 075 = 12 This represents that after storing 12th
key-value pair into the HashMap, its capacity will become 32
HashMap Class Methods:
Method Description
value put (key, value) This method stores key-value pair into the HashMap
value get (Object key) This method returns the corresponding value when key is given If
the key does not have a value associated with it, then it returns null
Set<K> keyset() This method, when applied on a HashMap converts it into a set
where only keys will be stored
Collection <V> values() This method, when applied on a HashMap object returns all the
values of the HashMap into a Collection object
value remove (Object key) This method removes the key and corresponding value from the
HashMap
void clear () This method removes all the key-value pairs from the map
boolean isEmpty () This method returns true if there are no key-value pairs in the
HashMap
int size () This method returns number of key-value pairs in the HashMap
83
82
. .
Systemoutprintln (set);
}
}
Output:
Hashtable Class: Hashtable is a collection that stores elements in the form of key-value
pairs If key is provided later its corresponding value can be easily retrieved from the
HAshtable Keys should be unique Hashtable is synchronized and hence while using
multiple threads on Hashtable object, we get reliable results
We can write Hashtable class as: class Hashtable<K,V>
For example to store a String as key and an integer object as its value, we can create the
Hashtable as: Hashtable<String, Integer> ht = new Hashtable<String, Integer> ();
The default initial capacity of this Hashtable will be taken as 11 and the load factor as 075
Load factor represents at what level the Hashtable capacity should be doubled For example,
the product of capacity and load factor = 11 * 075 = 825 This represents that after storing
8th key-value pair into the Hashtable, its capacity will become 22
Hashtable Class Methods:
Method Description
value put(key, value) This method stores key-value pair into the Hashtable
value get(Object key) This method returns the corresponding value when key is given If
the key does not have a value associated with it, then it returns null
Set<K> keyset() This method, when applied on a Hashtable converts it into a set
where only keys will be stored
Collection <V> values() This method, when applied on a Hashtable object returns all the
values of the Hashtable into a Collection object
value remove(Object key) This method removes the key and corresponding value from the
Hashtable
.
83
void clear() This method removes all the key-value pairs from the Hashtable
boolean isEmpty() This method returns true if there are no key-value pairs in the
Hashtable
int size() This method returns number of key-value pairs in the Hashtable
Arrays Class: Arrays class provides methods to perform certain operations on any single
dimensional array All the methods of the Arrays class are static, so they can be called in the
form of Arraysmethodname ()
Arrays Class Methods:
Method Description
static void sort (array) This method sorts all the elements of an array into ascending
order This method internally uses QuickSort algorithm
static void sort (array, int This method sorts the elements in the range from start to end
start, int end) within an array into ascending order
.
84
static int binarySearch This method searches for an element in the array and returns its
(array, element) position number If the element is not found in the array, it returns
a negative value Note that this method acts only on an array
which is sorted in ascending order This method internally uses
BinarySearch algorithm
static boolean equals This method returns true if two arrays, that is array1 and array2
(array1, array2) are equal, otherwise false
static array copyOf (source- This method copies n elements from the source-array into another
array, int n) array and returns the array
static void fill (array, value) This method fills the array with the specified value It means that
all the elements in the array will receive that value
Program 8: Write a program to sort given numbers using sort () method of Arrays Class
import javautil*;
//Arrays Demo
class ArraysDemo
{public static void main(String args[])
{
int x[] =
{40,50,10,30,20};
Arrayssort( x );
for (int i=0;i<xlength;i++)
Systemoutprint(x[i] +
"\t");
}
}
Output:
StringTokenizer: The StringTokenizer class is useful to break a String into small pieces
called tokens We can create an object to StringTokenizer as:
StringTokenizer st = new StringTokenizer (str, "delimeter");
StringTokenizer Class Methods:
Method Description
String nextToken() Returns the next token from the StringTokenizer
boolean hasMoreTokens() Returns true if token is available and returns false if not available
int countTokens() Returns the number of tokens available
while ( sthasMoreTokens () )
{
String s = stnextToken
(); Systemoutprintln (s
);
}
}
}
Output:
Calendar: This class is useful to handle date and time We can create an object to Calendar
class
as: Calendar cl = CalendargetInstance ();
Calendar Class Methods:
Method Description
int get(Constant) This method returns the value of the given Calendar constant
Examples of Constants are CalendarDATE, CalendarMONTH,
CalendarYEAR, CalendarMINUTE, CalendarSECOND,
CalendarHour
void set(int field, int value) This method sets the given field in Calendar Object to the given
value For example, clset(CalendarDATE,15);
String toString() This method returns the String representation of the Calendar
object
This method compares the Calendar object with another object
boolean equals(Object obj) obj
and returns true if they are same, otherwise false
//Retrieve Date
86
Date Class: Date Class is also useful to handle date and time Once Date class object is
created, it should be formatted using the following methods of DateFormat class of javatext
packageWe
can create an object to Date class as: Date dd = new Date ();
Once Date class object is created, it should be formatted using the methods of DateFormat
class of javatext package
DateFormat class Methods:
DateFormat fmt = DateFormatgetDateInstance(formatconst, region);
This method is useful to store format information for date value into DateFormat object
fmt
DateFormat fmt = DateFormatgetTimeInstance(formatconst, region);
This method is useful to store format information for time value into DateFormat object
fmt
DateFormat fmt = DateFormatgetDateTimeInstance(formatconst, formatconst, region);
This method is useful to store format information for date value into DateFormat
object fmt
Formatconst Example (region=LocaleUK)
03 september
DateFormatFULL 2007 19:43:14 O'Clock GMT + 05:30
03 september
DateFormatLONG 2007 19:43:14 GMT + 05:30
03-sep-07
DateFormatMEDIUM 19:43:14
DateFormatSHORT 03/09/07 19:43
Program 11: Write a program that shows the use of Date class
//Display System date and time using Date class
import javautil*;
import javatext*;
class MyDate
{
public static void main(String args[])
87
A Stream represents flow of data from one place to another place Input Streams reads or
accepts data Output Streams sends or writes data to some other place All streams are
represented as classes in javaio package The main advantage of using stream concept is to
achieve hardware independence This is because we need not change the stream in our
program even though we change the hardware Streams are of two types in Java:
Byte Streams: Handle data in the form of bits and bytes Byte streams are used to
handle any characters (text), images, audio and video files For example, to store an
image file (gif or
jpg), we should go for a byte stream To handle data in the form of 'bytes' the abstract
classes: InputStream and OutputStream are used The important classes of byte streams
are:
InputStream
BufferedInputStream DataInputStream
OutputStream
BufferedOutputStream DataOutputStream