SlideShare ist ein Scribd-Unternehmen logo
1 von 44
Downloaden Sie, um offline zu lesen
CollectionFramework Notes by Mr. Zeeshan
CollectionFramework
Definition: Collection is a java object that is used to group homogeneous and heterogeneous object’s
without size limitation for carrying multiple objects at a time from one application to anther application
among multiple layers of MVC architecture as method arguments and return type.
 java.util package contains several classes to group/collect homogeneous and heterogeneous
objects without size limitation. These classes are usually called collection framework classes.
Limitation of Object type Arrays:
1) Arrays are fixed in size:
 That is once we created an array there is no chance of increasing or decreasing the size based on
our requirement.
 Hence to use arrays concept compulsory we should know the size in advance, which mayn’t
possible always
2) Arrays can hold only homogeneous data type elements. String[] s=new
String[10];
s[0]=new String(); s[1]=new String();
s[2]="NIt"; we can overcome this limitation by using object type
Arrays.
Object o[]=new Object[10];
o[0]=new String();
o[1]=new String();
o[2]="NIt";
3) Arrays concept isn’t implemented based on some data structure hence ready
made method support isn’t available for arrays so for every requirement
programmer is responsible to write the code.
 To overcome the above limitations should go for collections.
 Collections are growable in nature that is based on our requirement we can increase or decrease
the size
 Collections can hold both homogeneous and heterogeneous elements.
 For every collection underlying data structure is available hence readymade method support is
available for the every requirement. Differentiate Arrays and collections:
Arrays Collection
Arrays are fixed in size Collections are grow able in nature
Arrays can hold only homogeneous data elements Collections can hold both homogeneous and
heterogeneous elements
With respect to memory arrays concept isn’t With respect to memory collections are recommended to use
recommended to use.
With respect to performance arrays are With respect to performance collection are not recommended
to use recommended to use
Arrays concept isn’t implemented based on some Every collection class is implemented based data
structure hence readymade method support On some data structure; hence for every
isn’t available requirement ready made method support is
available.
Arrays can hold both primitives and object type Collection can hold only object types but not
primitives.
CollectionFramework Notes by Mr. Zeeshan
Collection framework: It defines several classes and interface which can be used to represent group of
objects as single unit.
All the collection classes and interfaces are present in java.util package.
Sun developed many collection classes among them 15 are improtant,They are
LinkedList HashSet
HashMap
ArrayList‘ LinkedHashSet LinkedHashMap
Vector TreeSet TreeMap
Stack Hashtable PriorityQueue
Properties
In addition to collection classes SUN also defined some helper classes They
are
Collections Scanner Locale Date
Arrays StringTokenizer ResourceBundle Calendar
Random
Why the name collection framework?
Framework :- Framework is a semi finished reusable application which provides Some
common low level services and that can be customized accroding toour Requirements.
Java.util package classes are provides some low level services with well defined
Data structures to solve collection heterogeneous dynamic number of object’s
As a single unit.
Due to this reason java.util package classes are called collection f/w.
All the collection classes are implementing from java.io.Serializable so the collection
Object along with all it’s internal object’s can be stored in a local file system(OR) can
Be sent across n/w to remote computer.Here Rule is Object’s stored in collection are
Also should be serializable types to store collection in file.
In How many formats can we collect Object’s?
We can collect Objects in 2 ways
1) In Array Format—In this format object does not identity
2) In(key,value) pair formatIn this format object has identity
CollectionFramework Notes by Mr. Zeeshan
 Collection is an interface which can be used to represent a group of individual objects as a single
entity, where as collections are a utility class to define several utility methods for collection object.
In the above hierarchy, vector and stack classes are available since java 1.0, LinkedHashSet class is
available since java 1.4 queue is available since java 5,and NavigableSet is available since java 6, and all
other remaining classes and interfaces are available since java 1.2 version.
Map hierarchy:
Map hierarchy classes are used to collect elements in (key,value)pair format. In a map, keys should be
unique and values can be duplicated. Each (key,value) is called an entry . In map by default entries are not
sorted.
CollectionFramework Notes by Mr. Zeeshan
Collection interface:
 If we want to represent a group of individual object as a single entity then we should go for
collection.
 These interfaces define the most common general methods which are applicable for any collection
object.
 Commonly used methods of Collection interface:
 There are many methods declared in the Collection interface. They are as
follows:
 public boolean add(object element): is used to insert an element in this
collection.
 public boolean addAll(collection c):is used to insert the specifed collection
elements in the invoking collection.
 public boolean remove(object element):is used to delete an element from
this collection.
 public boolean removeAll(Collection c):is used to delete all the elements of
specified collection from the invoking collection.
 public boolean retainAll(Collection c):is used to delete all the elements of
invoking collection except the specified collection.
 public int size():return the total number of elements in the collection.
 public void clear():removes the total no of element from the collection.
 public boolean contains(object element):is used to search an element.
 public boolean containsAll(collection c):is used to search the specified
collection in this collection.
 public Iterator iterator():returns an iterator.
List interface:
 It is the child interface of collection.
 If we want to represent a group of individual objects where insertion order is preserved and
duplicates objects are allowed, then we should go for list.
 We can differentiate duplicate objects and we can maintain insertion order by using index, hence
index placed very important role in list.
 Commonly used mehtods of List Interface:
CollectionFramework Notes by Mr. Zeeshan
 public void add(int index,Object element);
 public boolean addAll(int index,Collection c);
 public object get(int Index position);
 public object set(int index,Object element);
 public object remove(int index);
 public ListIterator listIterator();
 public ListIterator listIterator(int i);
ArrayList class:
• ArrayList class extends AbstractList class and implements List interface.
• ArrayList Object allowed duplicate elements.
• ArrayList Object maintains insertion order.
• ArrayList Object is not synchronized.
• ArrayList Object accepts null value.
Note :-
Usually we can use collections to hold and transfer the data across network. To support this
requirement every collection class already implements serializable and clonable interfaces.
Array list classes and vector classes implements RandomAccess interface so that
We can access any Random element with the same speed
Hence if our frequent operation is retrieval operation ArrayList is the best choice.
ArrayList is worest choice if you want to perform insertion(or)deletion in the middle
.because internally several shift operations are required.
Hierarchy of ArrayList class:
ArrayList class Constructors :-
1) ArrayList():
CollectionFramework Notes by Mr. Zeeshan
Creates an empty arraylist obj with an intial capacity of 10(ten). If the
ArrayList object reaches it max capacity a new ArrayList object will be
created with
NewCapacity = currentCapacity*3/2+1
2) ArrayList(int intialcapacity)
Creates an empty arraylist obj with specified intial capacity.
3) ArrayList(Collection c) creates an equivalent ArrayList object for the
given collection
Listing 12.1 : Showing ArrayListDemo.java file
import java.util.*; class ArrayListDemo{
public static void main(String args[]){
ArrayList al=new ArrayList();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");//duplicated String object
al.add("Ajay");
al.add(null);
System.out.println(al);
}
}
Output:
Vector
class:
 The underlying data structure is resizable array or growable array.  Insertion order is preserved
 Duplication objects are allowed.
 Null insertion possible
 Implements Serializable, Consolable and RandomAceess interfaces.
 Every method present in vector is synchronized and hence vector object is Thread Safe
 Best suitable if our frequent operation is retrieval
 Worst choice if our frequent operations are insertion or deletion in the middle.
 Important methods of Vector class:
SN Methods with Description
1 void add(int index, Object element)
Inserts the specified element at the specified position in this Vector.
2 boolean add(Object o)
Appends the specified element to the end of this Vector.
CollectionFramework Notes by Mr. Zeeshan
3 boolean addAll(Collection c)
Appends all of the elements in the specified Collection to the end of this Vector, in
the order that they are returned by the specified Collection's Iterator.
4 boolean addAll(int index, Collection c)
Inserts all of the elements in in the specified Collection into this Vector at the
specified position.
5 void addElement(Object obj)
Adds the specified component to the end of this vector, increasing its size by one.
6 int capacity()
Returns the current capacity of this vector.
7 Object elementAt(int index)
Returns the component at the specified index.
8 Enumeration elements()
Returns an enumeration of the components of this vector.
9 Object get(int index)
Returns the element at the specified position in this Vector.
10 int indexOf(Object elem)
Searches for the first occurence of the given argument, testing for equality using
the equals method.
11 int lastIndexOf(Object elem)
Returns the index of the last occurrence of the specified object in this vector.
12 Object remove(int index)
Removes the element at the specified position in this Vector.
13 boolean remove(Object o)
Removes the first occurrence of the specified element in this Vector If the Vector
does not contain the element, it is unchanged.
14 boolean removeAll(Collection c)
Removes from this Vector all of its elements that are contained in the specified
Collection.
15 void removeAllElements()
Removes all components from this vector and sets its size to zero.
16 boolean removeElement(Object obj)
Removes the first (lowest-indexed) occurrence of the argument from this vector.
CollectionFramework Notes by Mr. Zeeshan
17 void removeElementAt(int index) removeElementAt(int
index)
18 int size()
Returns the number of components in this vector.
19 Object[] toArray()
Returns an array containing all of the elements in this Vector in the correct order.
20 Object[] toArray(Object[] a)
Returns an array containing all of the elements in this Vector in the correct order;
the runtime type of the returned array is that of the specified array.
21 void trimToSize()
Trims the capacity of this vector to be the vector's current size.
ArrayList , Vector:
 We should chose these two classes to store elements in indexed order and to retrieve them
randomly, it means retrieving the element directly without retrieving (n-1) elements ,because
these two classes are subclasses of RandomAccess interface.
 Functionalities of these two classes:
1) Duplicate objects are allowed in indexed order
2) Heterogeneous objects are allowed
3) Insertion order is preserved
4) Implemented datastructure is growable array.
5) Null insertion is possible, more than one null is allowed.
6) Initial capacity is 10, incremental capacity is double for Vector and ArrayList used below
formula(currentCapacity*3/2+1).whenever the collection object size reaches its max capacity, that
class internal API creates new collection object based on its incremental capacity value. Then in
new collection object old collection object elements are copied.
Vector object is thread-safe: It means synchronized object so multiple threads cannot modify this object
concurrently. It is best suitable in multithreaded model application to get desired result. But in single thread
model application it gives poor performance, activity in single thread model application. To solve this
performance issue in collection framework ArrayList class is given.
 ArrayList object is not thread-safe it means it is not synchronized object. It is best suitable in
multithreaded model application, also in multithreaded model application it you ensure there is not
data corruption.
Limitation: Inserting and removing elements in middle is costlier operation. Because for every insert
operation elements must move to right and for every delete operation elements must move to left from that
location.
CollectionFramework Notes by Mr. Zeeshan
To slove this issue we must choose LinkedList,It gives high Performance
In inserting (OR) deleting elements in Middle. It Internally uses Linked List
Data structure,so there will not be any data movements,instead we will have
Only changing links ,and indexes
The Example is showing Storing user-defined class objects into ArrayList
import java.util.ArrayList; import java.util.Iterator; class Student {
String name;
int rollno; String
course;
int fee;
Student(String name,int rollno,String course,int fee){ this.name=name;
this.rollno=rollno; this.course=course;
this.fee=fee;
}
public String toString(){
return "nName :"+name+
"nRoll No :"+rollno+
"nCourse :"+course+
"nFee :"+fee;
}
}
class ArrayListExample{
public static void main(String[] args){
Student s1=new Student("sathish",123,"java",800);
Student s2=new Student("venky",124,"c,c++",1000);
CollectionFramework Notes by Mr. Zeeshan
Student s3=new Student("3sha",125,"Oracle",500);
ArrayList al=new ArrayList();
al.add(s1);
al.add(s3); al.add(s2);
Iterator itr=al.iterator();
while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st);
}
}
}
Output :
The Example is showing Stroing the elements into Vector Object.
import java.util.*;
CollectionFramework Notes by Mr. Zeeshan
public class VectorExample
{
public static void main(String args[])
{
Vector vector = new Vector();
System.out.println("Initial size: " + vector.size());
System.out.println("Initial capacity: " +vector.capacity());
vector.addElement(new Integer(3)); vector.addElement(new
Integer(4)); vector.addElement(new Integer(5));
vector.addElement(new Integer(6)); vector.addElement(new
Double(6.35)); vector.addElement(new Double(7.98));
vector.addElement(new Integer(8)); vector.addElement(new
Float(10.4)); vector.addElement(new Integer(11));
vector.add("java");
vector.add("c");
System.out.println("First element: " +vector.firstElement());
System.out.println("Last element: " +vector.lastElement());
System.out.println("Vector Capacity after adding 11 elements:
"+vector.capacity());
System.out.println("Vector size after adding 11 elements:
"+vector.size());
System.out.println("nElements in vector: " + vector);
}
}
Output :
LinkedList class:
• LinkedList uses doubly linked list to store the elements. It extends the
AbstractList class and implements List and Deque interfaces.
• LinkedList object allows duplicate elements.
CollectionFramework Notes by Mr. Zeeshan
• LinkedList object maintains insertion order.
• LinkedList Object is not synchronized.
• LinkedList implements Serializable , clonable interfaces but not
RandomAccess.
• LinkedList best suitable our frequent operation is Insertion and deletion
• in the middle. Linked List is Worst choice if our frequent operation is retrievable
operation.
Listening 12.6 showing storing the elements into LinkedList
import java.util.*; class LinkedListDemo {
public static void main(String args[]) {
// create a linked list
LinkedList ll = new LinkedList();
// add elements to the linked list
ll.add("F");
ll.add("B");
ll.add("D");
ll.add("E");
ll.add("C");
ll.addLast("Z");
ll.addFirst("A");
ll.add(1, "A2");
System.out.println("Original contents of ll: " + ll);
// remove elements from the linked list
ll.remove("F");
ll.remove(2);
System.out.println("Contents of ll after deletion: "
+ ll);
// remove first and last elements
ll.removeFirst();
ll.removeLast();
System.out.println("ll after deleting first and last: "
+ ll);
// get and set a value
Object val = ll.get(2);
ll.set(2, (String) val + " Changed");
System.out.println("ll after change: " + ll);
}
}
Output :-
CollectionFramework Notes by Mr. Zeeshan
Generics:-
Introduction:-
case(i):-
once we created an array for a type we can add only that particular Type of objects.
By mistake if we are trying to add any other type we will get C.E:-
Hence we can give gurantee for the type of elements in array
and Hence arrays are Type -safe.
EX:-
String s[]=new String[100];
s[0]="AAA";
s[1]="BBB";
s[2]=10;//C.T.E
Hence we can give the gurantee that String array can contain only
String Type of Objects.
But Collections are not Type Safe,i.e we can't give the guarntee
for the type of elements in collection.
For Example if our programming requirement is to hold String objects and we can
choose ArrayList,by mistake if you are trying to add any other type we won't get
any compiletime Error. but there may be a chance of failing the app at runtime.
EX:-
CollectionFramework Notes by Mr. Zeeshan
ArrayList l=new ArrayList();
l.add("sathish");
l.add("nit");
l.add((100);
String s1=(String)l.set(0,"aaa");
String s2=(String)l.set(1,"sss");
String s3=(String)l.set(2,"ddd"); //R:Ex:--ClassCastException
There is no gurantee the collection can hold Type of objects.
Hence with respect to type, Arrays are Type safe to use.
Where as Collection are not safe to use.
case(ii):- ------- while reteriving Array elements it is not
required to perform TypeCasting .
we can assign Array Elements directly to the Corresponding Type variables.
String[] s=new String[10];
s[0]="Sathish";
s[1]="nit";
String s=s[0];//sathish
type casting is not required
But while reterieving elements from collection compulsary we should
perform Type casting. otherwise we will get CompileTimeError.
Hence TypeCasting is the biggest headck in collections.
to overcome the above problems of collections (Typesafety,Type casting)
sun micro systems has introduced Generics concept in java 5 version.
To Hold only String Type of Objects a Generic version of
ArrayList can declare as follows
ArrayList<String> l=new ArrayList<String>(); basetype
parametertype
for this arraylist we can hold only String type of objects, other wise we will get
CE:
2)Hence generics can provide TypeSafty to collections .
CollectionFramework Notes by Mr. Zeeshan
At time of reterival it is not required to perform TypeCasting.
Hence main objective of generics are
1) To provide TypeSafty for colletions
2) To reslove TypeCasting problem
Conclusion--I:- ---------------
EX:-
--
1) AL<String> l=new AL<String>();//valid
2) Al<Object> l=new AL<String>();//C.T.E:-
conclusion-II:- -------------
At the type parameter we can use any class
(or) Interface name
and we can't provide primitive Type.
1)AL<Integer> l=new AL<Integer>();
2) AL<int> l=new AL<int> ();//C.T.E:-
Generic class:- ---------------
non generic version of ArrayList class is declared as follows
class ArrayList
{
add(Object o) Object
get(int index)
} the add() method can take object as
argument .
Hence we can add any type of object to ArrayList .
Due to this we are not getting typesafty.
The return type of get(-)method is object hence at the time
of reterival compulsary we should perform type casting.
But from 1.5 version a generic version of ArrayList class is define as follows.
class ArrayList<T>{
add(T t) T
get(int index)
}
CollectionFramework Notes by Mr. Zeeshan
Based on our requirement "T" will be replaced with corresponding
Type.
-->Through Generics we can associate type parameter for the class such
type of parametrized classes are called Generic classes.
--> we can create our own Generic classes also
Ex:- class
Bank<T>
{
}
Bank<Icici> b=new Bank<Icici>();
Bounded Types:-
---------------------
We can bound the type parameters for a particular
rangesuch types are called bounded types.
Ex:- 1) class
Test<T>
{//UnBoundedType
}
as the type parameter we can pass any type
There are no restrictions.
Hence it is unbound type.
Ex:2)
class Test<T extends X> //x is class/interface
{
}
If X is a class then as the type parameter we can pass
either X type (or) it's sub classes.
If X is an interface then as the type parameter we can
pass either Xtype
(or) it's implementations classes.
CollectionFramework Notes by Mr. Zeeshan
Ex:-
class Test<T extends Number>{
}
Test<Integer> t=new Test<Integer>();
Test<String> t=new Test<String>();//C.T.E
we can bound the type parameters only by using extends
keyword. and we cannot bound by using implements and super
keywords.
Creation of our own generics:- -------
-------------------------------- class
Test<T>{
T obj;
Test(T obj) {
this.obj=obj;
}
public void show(){
System.out.println(" The Type of Obj is :"+obj.getClass().getName());
} public T
getObj(){ return
obj;
}
}
class GenericsDemo{
public static void main(String[] args) {
Test<String> g1=new Test<String>("Sathish");
g1.show();//the type obj is java.lang.String
System.out.println(g1.getObj());//sathish
Test<Integer> g2=new Test<Integer>(10);
g2.show();//java.lang.Integer System.out.println(g2.getObj());//10
Test<Double> g3=new Test<Double>(10.55);
g3.show();//java.lang.Double
System.out.println(g3.getObj());//10.55
}
}
CollectionFramework Notes by Mr. Zeeshan
Type Inference for Generic instance creation (or)
Diamond Syntax:-
---------------
You can replace the type arguments required to
invoke the constructor of a generic class with an
empty set of type parameters (< >) . This pair of
angle brackets is called the diamond.
For example, consider the following variable
declarations:
ArrayList<String> al=new ArrayList<>();// valid from java 7
ArrayList<Integer> al=new ArrayList<>();// valid from java 7
Note:
Collections are not Type Safe, i,e we can't give the guarantee for the type of
elements in collection. While retrieving elements from collection compulsory we
should perform Type casting. Otherwise we will get CompileTimeError. To
overcome the above problems of collections (Typesafety , Type casting)
Generics are introduced in JSE 5.0 version.
Hence main objective of generics are
1) To provide TypeSafty for C olletions
2) To reslove TypeCasting Problem
The 3 cursor’s of java:
 If we want to retrieve objects one by one from the collection then we should go for cursor.
 There are three cursors are available in java.
1) Enumaration
2) Iterator
3) ListIterator
Enumaration:
 We can use enumeration object to get the objects one by one from legacy collection objects.
 We can create enumeration object by using elements method
Enumaration e=v.elements();
 Enumeration interface defines the following two methods.
1) public boolean
hasMoreElements(); 2) public object
nextElement(); Ex:
CollectionFramework Notes by Mr. Zeeshan
import java.util.*; class
EnumarationDemo
{public static void main(String[] args) {
Vector v=new Vector();
for (int i = 0; i < 10; i++) {
v.addElement(i);
}
System.out.println(v);
Enumeration e=v.elements();
while(e.hasMoreElements())
{
Integer i=(Integer)e.nextElement();
if(i%2==0)
System.out.println(i);
}
System.out.println();
System.out.println(v);
}
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
2
4
6
8
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Limitations of Enumeration:
 Enumeration concept is applicable only for legacy classes.
 By using Enumeration we can get only read capability and we can’t perform remove operation.
To overcome the above limitations we should go for the Iterator.
Iterator:
 We can use Iterator for any collection object to get objects one by one from the Collection.
 While iterating objects by Iterator, we can perform remove operation in addition to read
operation.
 We can get Iterator object by using iterator() method on collection interface.
public Iterator iterator();
Iterator itr=c.iterator(); here c is any collection Object.
 Iterator interface defines the following three methods.
1) Public boolean hasNext();
2) Public object next();
3) Public void remove();
Exa:let’s developing below program above Iterator methods.
import java.util.*; class
EnumarationDemo {
public static void main(String[] args) {
ArrayList al=new ArrayList();
for (int i = 0; i < 10; i++) {
CollectionFramework Notes by Mr. Zeeshan
al.add(i);
}
System.out.println(al);
Iterator i=al.iterator();
while(i.hasNext())
{
Integer ele=(Integer)i.next();
if(ele%2==0)
System.out.println(ele);
else
i.remove();
}
System.out.println();
System.out.println(al);
}
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
2
4
6
8
[0, 2, 4, 6, 8]
Limitaitions of Iterator:
1) By using Enumeration and Iterator, we can always move towards forward direction and we
can’t move the backward direction, that is these are single direction cursors.
2) By using Iterator, we can perform only read and remove of operations and we cannot perform
replace operation on the addition of new objects.
To overcome above limitations we should go for ListIterator.
ListIterator:
1) It is the child interface of iterator. By using ListIterator we can move either to the forward
direction or to the backward direction.
2) It is a bidirectional cursor.
3) While iterating objects by ListIterator then we can perform replacement and addition of new
objects in addition to read and remove operations.
4) We can create ListIterator by using ListIterator() method of List(I). public ListIterator
listIterator()
ListIteator ltr=l.listIterator()--> here any list object.
ex: Let’s understand above concept to develop below program.
import java.util.*;
class ListIteratorDemo
{
public static void main(String[] args) {
LinkedList l=new LinkedList();
l.add("ramu");
l.add("raju");
l.add("sai");
l.add("sairam");
l.add("vijay");
System.out.println(l);
CollectionFramework Notes by Mr. Zeeshan
ListIterator li=l.listIterator();
while(li.hasNext()) {String
s=(String)li.next();
if(s.equals("ramu"))
{ li.remove();
System.out.println(s);
System.out.println();
}
System.out.println(s);
}
} }
Note:The most powerful cursor is ListIterator but its limitation is it is
applicable only for List object.
Set
 It is the child interface of collection.
 If we want to represent a group of individual objects where duplicates aren’t allowed and
insertion order isn’t preserved then we should go for Set.
 Set Interface doesn’t contain any new methods we have to use only collection interface methods
HashSet:
 The underlying data structure is “Hashtable”.
 Insertion order is n’t follows.
 Duplicate objects are n’t allowed and if we are trying to insert duplicate object we don’t get any
compile time or runtime exceptions, simple add() method returns false.
 Heterogeneous objects are allowed.
 null insertion is possible
 HashSet implements seriablizable and cloneable interface.
 If our frequent operation is SearchOperation then HashSet is best choice.
Constructor:
1) HashSet h=new HashSet();
Creates an empty HashSet object with the default initial capacity is 16 and default fillratio is
“.75”
2) HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with the specified initial capacity and default fillratio 0.75%.
3) HashSet h=new HashSet(int initialcapacity,float fillratio);
4) HashSet h=new HashSet(Collection c);
CollectionFramework Notes by Mr. Zeeshan
Ex:write a simple program using HashSet.
import java.util.HashSet; public class
HashSetDemo { public static void
main(String[] args) {
HashSet hs=new HashSet();
hs.add("a");
hs.add("b"); hs.add("c");
hs.add("d");
hs.add(null);
hs.add(10);
hs.add(null);//false
System.out.println(hs);
}
}
Output:
[null, d, b, c, a, 10]
Note :- refer HashSetDemo1,HashSetDemo2 example programms in folder
1) public native int hashCode():-
------------------------------------------
to get the hashCode of the object we can call hashCode().
we can override the hashCode() in the user-defined classes to create the Our own hashCodes by using
object state.
JVM will always uses these HashCodes while saving the Objects into Hashtable,HashMap and HashSet.
equals():-
----------
equals() method is given to compare two objects for their equality.
In java we can compare objetcs in two ways either.
1. By using Objects reference or
2.By using Objects state.
If two objects of a class are said to be equal only if their reference or state is equal.
we have to compare the objects either by
1. using == operator -->It always compares objects with their references.
2. using equals() method-->It always objects based on it's implementation.
equals() method implementation inside object class.
--------------------------------------------------------------
In object class this method is implemented to compare two objects with their references,as shown below
public boolean equals(Object obj){ return(this==obj);
}
this method return true if the current object reference is equals to argument object reference,else it return
false.
CollectionFramework Notes by Mr. Zeeshan
If we want to compare two objects with state we must override this method in sub class.
contract between equals() and hashCode():- if the equals() method return true by comparing two
objects,then hashCode of the both objects must be same.
If it returns false ,the hashCode of the both objects may(or) may not be same.
Difference b/w equals() and ==
== operator will only compare reference of the Objects.
Real world object's must be compared with thieir state.
it is not possible to override the== operator.
equals() is given by the sun to compare the object’s equals() will compares the Object’s
based on the implementation . in object class equals() was implemented to compare the
object’s with reference. If we want to compares the object’s with the state we can
Override the equals() method.
Note :-
Java Object's identity is called hashcode.It is a 32 bit random integer number created by jvm for every
object.
Each object will have a unique identity.
The hashcode of the object can be retrieved by using a method "hashcode()."
Developer can also generate hashcode of an object based on
the state of that object by overriding hashCode()
In this case ,if state is changed ,automatically hashCode will be changed .
Note :-
JVM generated hashCode will not be changed if object state is changed ,
HashCode is used when object is stored in HashTable .
LinkedHashSet:
 It is the child class of HashSet
 It is exactly same as HashSet(including constructor and method) except the following differences.
HashSet LinkedHashSet
The underlying data structure is Hashtable The underlying data structructure is the
combination of the Hashtable and LinkedList.
Insertion order isn’t preserved Insertion order is preserved.
Introduced in 1.2 version Introduced in 1.4 version.
Ex:write a sample program using LinkedHashSet
CollectionFramework Notes by Mr. Zeeshan
import java.util.HashSet; import
java.util.LinkedHashSet; public
class LinkedHashSetDemo {
public static void main(String[] args) {
LinkedHashSet hs=new LinkedHashSet();
hs.add("a"); hs.add("b");
hs.add("c"); hs.add("d");
hs.add(null);
hs.add(10);
hs.add(null);//false
System.out.println(hs);
}
}
Output:
[a, b, c, d, null, 10] sortedSet:
 It is the child interface of Set
 If we want to represent a group of individual objects according to some sorting order without
duplicates, then we should go fro SortedSet.
 SortedSet interface defines the following methods.
1) Object first()
Return first element of the sortedSet.
2) Object last()returns last element of the SortedSet.
3) SortedSet headset(Object ob)
Retruns sortedset whose elements are less than ob.
4) SortedSet tailSet(Object ob)
Retruns sortedset whose elements are greater than ob.
5) SortedSet subset(object obj1,object obj2)
Return sortedSet whose elements are greater then or equal to obj1 and less than obje2.
6) Comparator comparator()
Return comparator obj , which describe underlying sorting technique.
TreeSet:
 Underlying data structure is BalancedTree
 Duplicate objects aren’t allowed
 Insertion order isn’t preserved and it is based on the some SortingOrder.
 Null insertion is possible (only once) when it is the first element.
 Heterogeneous objects aren’t allowed and if we are trying to insert the heterogeneous objects we
will get the RuntimeeException saying ClassCastException.
Constructor:
1) TreeSet t=new TreeSet();
If crates an empty TreesSet object wher all objects will be inserted according to Natural
sorting order.
2) TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be inserted according to customized
Sorting order, which is the described by comparator object.
3) TreeSet t=new TreeSet(SortedSet c);
4) TreeSet t=new TreeSet(Collection c);
Null acceptance:
CollectionFramework Notes by Mr. Zeeshan
For the nonempty TreeSet, if we are trying to inserting the null and we will get NullpointerException
 For the empty TreeSet, as the first element null insertion is possible. But after inserting that null if
we are trying to insert any other element then we will get NullpointerException.
From java 7 empty tree set also not allows the null value.
Refer the Example Programms in the ClassRoom
Programms Folder
Difference between comparable and comparator interfaces:
Comparable interface:
 Comparable interface present in java.lang package and it contains only one method that is
compareTo()
public int compareTo(Object obj) obj1.compareTo(obj2)here return “-v” when obj1 has
to place before obj2.return “+v”if
and only obj1 has to place after obj2.return “0” if and only obj1 and obj2 both are
equal.
 Comparable used to specify natural sorting order internally jvm will call compareTo () method to
place objects into the TreeSet.
import java.util.TreeSet; class SetClassDemo {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add("a");
ts.add("z");
ts.add("c");
System.out.println(ts);}
}
Output: acz
Below diagram how to check internal in compareTo() method:
CollectionFramework Notes by Mr. Zeeshan
 Comparable is meant for default natural sorting order where as comparator is meant for
customized sorting order. Comparator(I):
 This interface present in java.util package and contains the following two methods. public int
compare(Object obj1,Object obj2) public Boolean equals(Object obj)
 Whenever we are implementing comparator interface compulsory we should provide
implementation for compare () method.
 Implementing equals () method is optional because it is already available in every java class
from object class.
Ex: Write a program using comparable interface.
import java.util.TreeSet;
class Address implements Comparable
{int x;
Address() {}
Address(int x) {
this.x=x;
}
public int compareTo(Object obj)
{
Address a=(Address)obj;
return a.x=this.x;
}
public String toString()
{
return ""+x;
}
}
import java.util.TreeSet; public
class AddingCustomobjects {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add(new Address());
ts.add(new Address(20));
ts.add(new Address());
ts.add(new Address(5));
ts.add(new Address(30));
ts.add(new Address(20));
ts.add(new Address());
System.out.println(ts.size());
System.out.println(ts);
}
}
Output:
5
[5, 0, 20, 20, 20]
Ex#2: Write a program using comparator interface.
import java.util.Comparator; import
java.util.TreeSet;
class StringComparator implements Comparator
{
CollectionFramework Notes by Mr. Zeeshan
public int compare(Object ob1, Object ob2) {
String astr,bstr;
astr=(String)ob1;
bstr=(String)ob2;
return bstr.compareTo(astr);
}
}
class ComparatorDemo{ public static void
main(String[] args) {
TreeSet ts=new TreeSet();
ts.add("A");
ts.add("B"); ts.add("C");
ts.add("N");
System.out.println("ts object with default comparator"+ts);
TreeSet tsc=new TreeSet(new StringComparator());
tsc.add("A");
tsc.add("B"); tsc.add("C");
tsc.add("N");
tsc.add("z");
System.out.println("ts object with custom comparator"+tsc);
}
}
Output:
ts object with default comparator[A, B, C, N] ts
object with custom comparator[z, N, C, B, A]
Remaining example lab exercise ex#2.
Comparable v/s Comparator:
 For predefined comparable classes like String default natural Sorting order is already available. If
we aren’t satisfied with that natural sorting order we can define own sorting by Comparator
object.
 For predefined non Comparable classes like StringBuffer the default natural sorting order isn’t
already available, we can define our own sorting by Comparator.
 For our own classes the person who is writing the class he can define default natural sorting order
by implementing comparable interface.
 The person who is using our own classes, if he isn’t satisfied with default natural sorting order,
then he can define his own sorting by using comparator object.
Comparable Comparator
 This interface meant for default natural
sorting order
 This interface meant for the customized
sorting order
 This interface present in default java.lang
package
This interface present in the java.util package.
CollectionFramework Notes by Mr. Zeeshan
 It defines only one method compareTo() It defines two
methods compare()
equals()
Sorting class, all wrapper classes
implements Comparable interface
The only implemented classes of comparator
interface are
 Collator
 RuleBasedCollator.
Conclusion: comparison table of Set implemented class
property HashSet LinkedHashSet TreeSet
 Underlying
ofthe
datastructure
Hashtable Hashtable+likedList BlancedTree
 Insertion order Not preserved Preserved Not preserved
 Sorting order Not applicable Not applicable applicable
Heterogeneous object allowed Allowed Not allowed
Duplicate object Not allowed Not allowed Not allowed
Null acceptance allowed Allowed As the first
element null
is allowed. In
all reaming
case we will
get NPE.
Map interface:
 Map is n’t child interface of Collection.
 If we want to represent a group of objects as key,value pairs then we should go for Map.
 Both key and value are objects only.
 Duplicate keys aren’t allowed but the values can be duplicated.
 In map Each key,value pair is called as one entry.
CollectionFramework Notes by Mr. Zeeshan
Map interface methods:
1) Object put(Object key,Object value) to insert one key and value pair (Entry) to the Map.
 If the specified key is already available then old value is replaced with new value and the old value
will be return.
2) void putAll(Map m) to insert a group of key,value pairs
3) Object get(Object key) to get value associated with specified key.
4) boolean containsKey(Object key) used to check the the specified key is available (OR) not
5) boolean containsValue(Object value) used to check the the specified value is available (OR)
not
6) boolean isEmpty() used to to check the map is empty or not.
7) int size()used to get the size of the map object
8) void clear()  used to clear the map object
9) Object remove(Object key)  used to remove entry based on the specified key.
10) Set keyset()this method returns all the key’s of a map object
11) Collection values()this method return’s all the alues of the map
12) Set entrySet()this method returns the all the entries of the map
Entry interface:
Entry is an Inner interface of Map
Each key,value pair is called as one entry .Hence map is considered as a group of Entries.
Without existing map object there is no chance of existing entry
object. Methods of Entry interface:- public Object getKey() public
Object getValue()
 HashMap:
 The underlying datastructure is Hashtable.
 Insertion order is n’t follows.
 Duplicate key’s aren’t allowed but the values can be duplicated.
 Heterogeneous objects are allowed for both keys and values
CollectionFramework Notes by Mr. Zeeshan
 Null keys are allowed for key (only once)and for the values (any no of times)
HashMap Hashtable
no method is synchronized every method is synchronized
HashMap object can be accessed by
multiple threads and hence it isn’t
Thread safe.
Hashtable object can be accessed by only one
thread at a time and hence it is thread safe.
Relatively performance is high. Relatively performance is low.
We can insert null for both key and
values
Null isn’t allowed for both key and values
otherwise we will get NullPointerEx
Introduced in 1.2 version
It is non legacy.
Introduced in 1.0 version and it is legacy.
Constructor:
1) HashMap m=new HashMap();
Creates an empty hashmap() object with default initial capacity is 16 and default fillratio is .75
2) HashMap m=new HashMap(int initialcapacity);
3) HashMap m=new HashMap(int initialcapacity,float fillratio);
4) HashMap m=new HashMap(Map m);
Refer the examples in the classroomExampleProgramms folder
LinkedHashMap:
 It is exactly same as HashMap except the following differences.
 The underlying datastructure is Hashtable,the underlying datastructure is a combination of
Hashtable +LinkedList.
 In LinkedHashMap Insertion is presereved ,but in the HashMap Insertion Order is not preserved
IdentityHashMap :
Identity HashMap is the Implemented class of Map interface.Identity HashMap is same as
HashMap Except the following differencs.
For identifying duplicate keys In the case of HashMap JVM Uses equals() method, Where as
In the case of
Identity HashMap JVM Uses the “==” (double equal) operator.
WeakHashMap:-
WeakHashMap is the Implemented class of Map interface.WeakHashMap is same as HashMap
Except the following differences.
CollectionFramework Notes by Mr. Zeeshan
• In case of HashMap an Object is not eligible for garbage collection if it is associated with
HashMap . Even though it doesnt have any external references. i.e, HashMap dominates
garbage collector.
• But in case of WeakHashMap ,if an Object is not having any external references then it is
always eligible for garabage collector even though it is associated with WeakHashMap . i.e,
garbage collector dominates WeakHashMap
Sorted Map interface :
• The Collection Framework provides a special Map interface for maintaining elements in a
sorted order called SortedMap . SortedMap is the sub interface of Map.
• If we want to represent a group of key value pairs according to some sorting order of keys
then we should go for Sorted Map.
• In Sorted Map we can perform sorting only based on the keys but not values.
SortedMap interface Specifc Methods
Object firstKey() object lastKey()
SortedMap headMap(Object key)
SortedMap tailMap(Object key)
Sotredmap subMap(Object key1,Object key2)
Comparator comparator()
Note : Working with a SortedMap is just similar to a SortedSet except, the sort is done on the
map keys.
NavigableMap
The java.util.NavigableMap(java 1.6) interface is a subinterface of the java.util.SortedMap
interface. It has a few extensions to the SortedSet which makes it possible to navigate the map. I
will take a closer look at these navigation methods in this text.
The java.util package only has one implementation of the NavigableMap interface:
java.util.TreeMap.
Here is a list of the topics covered in this text:
1. descendingKeySet() and descendingMap()
2. headMap(), tailMap() and subMap()
3. ceilingKey(), floorKey(), higherKey() and lowerKey()
4. ceilingEntry(), floorEntry(), higherEntry() and lowerEntry()
5. pollFirstEntry() and pollLastEntry()
6. descendingKeySet() and descendingMap() :
The first interesting navigation methods are the descendingKeySet() and descendingMap()
methods.
The descendingKeySet() method returns a NavigableSet in which the order of the elements
is reversed compared to the original key set. The returned "view" is backed by the original
NavigableSet ket set, so changes to the descending set are also reflected in the original set.
CollectionFramework Notes by Mr. Zeeshan
However, you should not remove elements directly from the key set. Use the Map.remove()
method instead.
Here is a simple example:
NavigableSet reverse = map.descendingKeySet();
The descendingMap() method returns a NavigableMap which is a view of the original Map.
The order of the elements in this view map is reverse of the order of the original map. Being a
view of the original map, any changes to this view is also reflected in the original map. Here is a
simple example:
NavigableMap descending = map.descendingMap();
headMap(), tailMap() and subMap() :
The headMap() method returns a view of the original NavigableMap which only contains
elements that are "less than" the given element. Here is an example:
NavigableMap original = new TreeMap();
original.put("1", "1");
original.put("2", "2");
original.put("3", "3");
//this headmap1 will contain "1" and "2"
SortedMap headmap1 = original.headMap("3");
//this headmap2 will contain "1", "2", and "3" because "inclusive"=true
NavigableMap headmap2 = original.headMap("3", true);
The tailMap() method works the same way, except it returns all elements that are higher
than the given parameter element.
The subMap() allows you to pass two parameters demarcating the boundaries of the view
map to return. Here is an example:
CollectionFramework Notes by Mr. Zeeshan
NavigableMap original = new TreeMap();
original.put("1", "1");
original.add("2", "2");
original.add("3", "3");
original.add("4", "4");
original.add("5", "5");
//this submap1 will contain "3", "3"
SortedMap submap1 = original.subMap("2", "4");
//this submap2 will contain ("2", "2") ("3", "3") and ("4", "4") because
// fromInclusive=true, and toInclusive=true
NavigableMap submap2 = original.subMap("2", true, "4", true);
ceilingKey(), floorKey(), higherKey() and lowerKey() :
The ceilingKey() method returns the least (smallest) key in this map that is greater than or
equal to the element passed as parameter to the ceilingKey() method. Here is an example:
NavigableMap original = new TreeMap();
original.put("1", "1");
original.put("2", "2");
original.put("3", "3");
//ceilingKey will be "2".
Object ceilingKey = original.ceilingKey("2");
//floorKey will be "2".
Object floorKey = original.floorKey("2");
The floorKey() method does the opposite of ceilingKey()
The higherKey() method returns the least (smallest) element in this map that is greater than (not
equal too) the element passed as parameter to the higherKey() method. Here is an example:
NavigableMap original = new TreeMap();
original.put("1", "1");
original.put("2", "2");
original.put("3", "3"); //higherKey
will be "3".
Object higherKey = original.higherKey("2");
//lowerKey will be "1"
Object lowerKey = original.lowerKey("2");
The lowerKey() method does the opposite of the higherKey() method.
celingEntry(), floorEntry(), higherEntry(), lowerEntry() :
CollectionFramework Notes by Mr. Zeeshan
The NavigableMap also has methods to get the entry for a given key, rather than the key itself.
These methods behave like the ceilingKey() etc. methods, except they return an Map.Entry instead
of the key object itself.
A Map.Entry maps a single key to a single value.
Here is a simple example. For more details, check out the JavaDoc.
NavigableMap original = new TreeMap();
original.put("1", "1");
original.put("2", "2");
original.put("3", "3");
//higherEntry will be ("3", "3").
Map.Entry higherEntry = original.higherEntry("2");
//lowerEntry will be ("1", "1")
Map.Entry lowerEntry = original.lowerEntry("2");
pollFirstEntry() and pollLastEntry() :
The pollFirstEntry() method returns and removes the "first" entry (key + value) in the
NavigableMap or null if the map is empty. The pollLastEntry() returns and removes the "last"
element in the map or null if the map is empty. "First" means smallest element according to the
sort order of the keys. "Last" means largest key according to the element sorting order of the map.
Here are two examples:
NavigableMap original = new TreeMap();
original.put("1", "1");
original.put("2", "2");
original.put("3", "3");
//first is ("1", "1")
Map.Entry first = original.pollFirstEntry();
//last is ("3", "3")
Map.Entry last = original.pollLastEntry();
TreeMap:
 The underlying datastructure is RED-BLACK Tree
 Duplicate keys aren’t allowed but the values can be duplicated.
 Insertion order isn’t preserved and all entries will be inserted according to some sorting order of
keys
 If we are depending on default natural sorting order then compulsory keys should be
homogeneous and comparable otherwise we will get ClassCastException.
But if we are defining our own sorting by comparator then the keys need n’t be comparable and
homogeneous.
 There are no restication for values, they can be heterogeneous and non comparable.
 Upto java 6 version For empty TreeMap as first entry with null key is allowed but after inserting
the entry .if we are trying to insert any other entry we will get “NullpointerException“.
 Upto java 6 version For non empty TreeMap if we are trying to insert an entry with null key then
we will get NPE.
CollectionFramework Notes by Mr. Zeeshan
 But From java 7 version null key’s are not allowed .
 There are no restrictions for null values.
Constructors:
1) TreeMap tm=new TreeMap()
For default natural sorting order.
2) TreeMap tm=new TreeMap(Comparator c)
For customized sorting order.
3) TreeMap tm=new TreeMap(SortedMap c)
Interconversion of sortedMap
4) TreeMap tm=new TreeMap(Map c)
Interconversion between Map.
Hashtable:
 Underlying datastructure for Hashtable is Hashtable
 Duplicate keys aren’t allowed but values can be duplicated
 Insertion order isn’t preserved and it is based on Hashcode of the keys.
 Heterogeneous objects are allowed for both keys and values.
 Null insertion isn’t possible fore both key and value otherwise we will get NPE.
 Every method present in Hashtable is synchronized and hence Hashtable object is Threadsafe.
Constructor:
1) Hashtable h =new Hashtable();
 Creates an empty Hashtable object with default initial capacity “11” and default fillration .75.
2) Hashtable h =new Hashtable(int initialcapacity);
3) Hashtable h =new Hashtable(int initialcapacity,float fillratio); 4) Hashtable h
=new Hashtable(Map);
HashtableDemo.java import
java.util.Enumeration; import
java.util.Hashtable; import
java.util.Set; public class
HashtableDemo { public static void
main(String args[]) { // Creating
Hashtable for example
Hashtable companies = new Hashtable(); //
to put object into Hashtable
companies.put("Google", "United States");
companies.put("Nokia", "Finland");
companies.put("Sony", "Japan");
// to get Object from Hashtable
companies.get("Google");
// Use containsKey(Object) method to check if an Object exits as key in
// hashtable
System.out.println("Does hashtable contains Google as key: "
+ companies.containsKey("Google"));
/* just like containsKey(), containsValue returns true if hashtable contains
specified object as value*/
CollectionFramework Notes by Mr. Zeeshan
System.out.println("Does hashtable contains Japan as value: "
+ companies.containsValue("Japan"));
// Hashtable elements() return enumeration of all hashtable values
Enumeration enumeration = companies.elements();
while (enumeration.hasMoreElements()) {
System.out.println("hashtable values: " + enumeration.nextElement());
}
// use size() method to find size of hashtable in Java
System.out.println("Size of hashtable in Java: " + companies.size());
// use keySet() method to get a Set of all the keys of hashtable
Set hashtableKeys = companies.keySet();
// get enumeration of all keys by using method keys()
Enumeration hashtableKeysEnum = companies.keys();
}
}
Output :
Properties:
 In our program if any thing which changes frequently( like username, password etc) are never
recommended to hardcode those values in our java program because for every change we have to
recompile ,rebuilt, redeploy application and sometimes we have to restart server is also required
which creates a big business impact to the client.
 Such type of values we have to place inside the properties file and we have to read those values
from the properties file into the java application.
 The main advantage of this application is if any change in properties file to reflect those changes
just redeployment is enough which won’t create any business object to hold properties from the
properties file.
 Properties class is the child class of the Hashtable and both key and values should be String type.
Constructor:
1) Properties p =new Properties();
Methods:
1) String getProperty(String pname);
Return the value associated with specified property.
2) String setProperty(string pname,string pvalue) To add a new property
3) Enumaration propertyNames();
4) Void load (InputStream is)
To load properties from properties file into java properties object.
5) void store(OutputStream os,String comment) to store the properties from java application into
Properties file.
Ex:
CollectionFramework Notes by Mr. Zeeshan
import java.io.FileInputStream;
import
java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import
java.util.Properties;
class propertiesDemo
{
public static void main(String[] args) throws IOException {
Properties p=new Properties();
FileInputStream fis=new FileInputStream("src/nit.properties");
p.load(fis);
System.out.println(p);
String s=p.getProperty("nit");
System.out.println(s);
p.setProperty("nit", "9090");
FileOutputStream fos=new FileOutputStream("abc.properties");
p.store(fos, "update is successfully");
}
}
Output abc.properties
#update is successfully
#Sat Aug 24 21:00:20 GMT+05:30 2013
laxman=core java nit=9090
java.util.Collections:
Collections class provides static methods for sorting the elements of collection .If
collection elements are of Set type, directly we can use TreeSet. But We cannot sort
the elements of List .So Collections class provides methods for sorting the elements of
List type elements.
Method of Collections class for sorting List elements
public void sort(List list): is used to sort the elements of List. List elements
must be of Comparable type.
Note: String class and Wrapper classes implements the Comparable
interface.So if you store the objects of string or wrapper classes, it will be
Comparable.
public void sort(List list,Comparator c): is used to sort the elements of List by the given
comparator.
The following example showing how to Sort the elements of List that contains
user-defined class objects .
CollectionFramework Notes by Mr. Zeeshan
import java.util.*;
class Student implements Comparable{ int
rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno; this.name=name;
this.age=age;
}
public String toString(){
return "name = "+name+" rollno = "+rollno+" age = "+age+"n";
}
public int compareTo(Object obj){
Student st=(Student)obj;
if(age==st.age)
return 0; else
if(age>st.age)
return 1;
else return
-1;
}
}
class ArrayListSortDemo{
public static void main(String args[]){
ArrayList al=new ArrayList(); al.add(new
Student(101,"Vijay",23)); al.add(new
Student(106,"Ajay",27)); al.add(new
Student(105,"Jai",21));
System.out.println("Before Sorting :");
System.out.println(al);
Collections.sort(al);
System.out.println("After Sorting :");
System.out.println(al);
}
}
Output :
CollectionFramework Notes by Mr. Zeeshan
Student class contains three fields rollno, name and age and a parameterized
constructor.
class Student { int
rollno;
String name; int
age;
Student(int rollno,String name,int age){
this.rollno=rollno; this.name=name;
this.age=age;
}
public String toString(){
return "name = "+name+" rollno = "+rollno+" age = "+age+"n";
}
}
The following example showing AgeComparator.java
AgeComparator class defines comparison logic based on the age. If age of first object
is greater than the second, we are returning positive value, it can be any one such as
CollectionFramework Notes by Mr. Zeeshan
1, 2 , 10 etc. If age of first object is less than the second object, we are returning
negative value, it can be any negative value and if age of both objects are equal, we
are returning 0.
import java.util.Comparator; class
AgeComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1;
Student s2=(Student)o2;
if(s1.age==s2.age)
return 0; else
if(s1.age>s2.age) return
1; else
return -1;
}
}
The following example showing NameComparator.java
NameComparator class provides comparison logic based on the name. In such case,
we are using the compareTo() method of String class, which internally provides the
comparison logic.
import java.util.Comparator;
class NameComparator implements Comparator{
public int compare(Object o1,Object o2){
Student s1=(Student)o1; Student
s2=(Student)o2;
return s1.name.compareTo(s2.name);
}
}
CollectionFramework Notes by Mr. Zeeshan
The following example showing ArrayListDemo.java
In ArrayList class, we are printing the objects values by sorting on the basis of name
and age.
import java.util.ArrayList; import
java.util.Collections; import
java.util.Iterator; class ArrayListDemo{
public static void main(String args[]){
ArrayList al=new ArrayList(); al.add(new
Student(101,"Vijay",23)); al.add(new
Student(106,"Ajay",27)); al.add(new
Student(105,"Jai",21));
System.out.println("Sorting by
Name...");
Collections.sort(al,new NameComparator());
Iterator itr=al.iterator(); while(itr.hasNext()){
Student st=(Student)itr.next();
System.out.println(st);
}
System.out.println("sorting by age...");
Collections.sort(al,new AgeComparator());
Iterator itr2=al.iterator();
while(itr2.hasNext()){
Student st=(Student)itr2.next();
System.out.println(st);
}
}
}
CollectionFramework Notes by Mr. Zeeshan
Output :
Queue interface:
 It is the child interface of collection.
 If we want to represent a group of individual objects prior to processing then we should go for
queue interface.
 From 1.5 versions onwards LinkedList also implements from queue interface.
 Usually queue first in first out order (fifo) but based on our requirement we can implement our
own order also.
 LinkedList based implementation of queue always follows fifo only. Queue interface specific
methods:
1) Boolean offer(Object o) to insert an object into the queue.
2) Object peek() it returns head element of the queue , if queue is empty then this method
returns null.
3) Object element () it returns head element of the queue and if Queue is empty then we will get
the runtime exception saying NoSuchElementException.
4) Object poll() to remove and return head element of the queue and if the queue is empty then
we will get null.
5) Object remove() to remove and return head element of the queue and if the queue is empty
then we will get RuntimeException.
priorityQueue:
 It is a datastructure where all objects will be arranged according to some priority , prior to
processing.
CollectionFramework Notes by Mr. Zeeshan
 The priority order can be either default natural sorting order or customized sorting order
specified comparator object.
 Duplicate objects aren’t allowed.
 Null insertion isn’t possible even as the first element also.
 If we are depending on default natural sorting order then the objects should be homogeneous and
comparable otherwise we will get ClassCastException.
 If we are defining our own sorting then the objects needn’t be comparable and homogeneous.
Constructors:
1) New PriotityQueue()creates an empty priorityQueue with default initial capacity 11
and sorting order is default natural sorting order.
2) new PriorityQueue(int initialcapacity)
3) new priorityQueue(int initialcapacity, comparator c);
4) new PriorityQueue(SortedSet ss)
5) new PriorityQueue(int initialcapacity)
6) new PriorityQueue(collection c)
ex: let’s write a program above
concept. import java.util.PriorityQueue;
public class priorityQueueDemo {
public static void main(String[] args) {
PriorityQueue pq=new PriorityQueue();
for (int i = 0; i < 10; i++) {
pq.offer(i);
}
System.out.println(pq);
System.out.println(pq.poll());
System.out.println(pq);
}
}
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
0
[1, 3, 2, 7, 4, 5, 6, 9, 8]
NavigableSet:
 It is the child interface of sortedSet.
 This interface defines the following methods which are useful for navigation purposes.
Methods:
1) floor(e)
 It return highest element which is <=e
2) lower(e)
 It returns element which is <e.
3) ceiling(e) it returns lowest element which is >=e.
4) higher(e) it returns lowest element which is >e.
5) pollFirst() remove and return first element
6) pollLast() remove and return last element
7) descendingSet() it returns NavigableSet in revers order.
CollectionFramework Notes by Mr. Zeeshan
Ex:
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.TreeSet; class
NavigatableSetDemo {
public static void main(String[] args) {
TreeSet ts=new TreeSet();
ts.add(1000); ts.add(2000);
ts.add(3000); ts.add(5000);
System.out.println(ts);
}
}
Output: [1000, 2000, 3000,
5000]

Weitere ähnliche Inhalte

Was ist angesagt?

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 

Was ist angesagt? (20)

Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
 
Java Collection framework
Java Collection frameworkJava Collection framework
Java Collection framework
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Java util
Java utilJava util
Java util
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
java collections
java collectionsjava collections
java collections
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Collections in Java
Collections in JavaCollections in Java
Collections in Java
 
07 java collection
07 java collection07 java collection
07 java collection
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 

Ähnlich wie Collection framework (completenotes) zeeshan (20)

collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
 
Advanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptxAdvanced Java - UNIT 3.pptx
Advanced Java - UNIT 3.pptx
 
Collections
CollectionsCollections
Collections
 
Java collections
Java collectionsJava collections
Java collections
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
Java.util
Java.utilJava.util
Java.util
 
Collection Framework-1.pptx
Collection Framework-1.pptxCollection Framework-1.pptx
Collection Framework-1.pptx
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Oops
OopsOops
Oops
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
 
Generics collections
Generics collectionsGenerics collections
Generics collections
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
Java Unit 2(part 3)
Java Unit 2(part 3)Java Unit 2(part 3)
Java Unit 2(part 3)
 
11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt11000121065_NAITIK CHATTERJEE.ppt
11000121065_NAITIK CHATTERJEE.ppt
 
Collections framework
Collections frameworkCollections framework
Collections framework
 
20 ch22 collections
20 ch22 collections20 ch22 collections
20 ch22 collections
 
Java collections
Java collectionsJava collections
Java collections
 

Mehr von Zeeshan Khan

Mehr von Zeeshan Khan (12)

Apache kafka
Apache kafkaApache kafka
Apache kafka
 
Spring security4.x
Spring security4.xSpring security4.x
Spring security4.x
 
Micro services overview
Micro services overviewMicro services overview
Micro services overview
 
XML / WEB SERVICES & RESTful Services
XML / WEB SERVICES & RESTful ServicesXML / WEB SERVICES & RESTful Services
XML / WEB SERVICES & RESTful Services
 
Manual Testing
Manual TestingManual Testing
Manual Testing
 
JUnit with_mocking
JUnit with_mockingJUnit with_mocking
JUnit with_mocking
 
OOPS in Java
OOPS in JavaOOPS in Java
OOPS in Java
 
Java
JavaJava
Java
 
Introduction to BIG DATA
Introduction to BIG DATA Introduction to BIG DATA
Introduction to BIG DATA
 
Big data
Big dataBig data
Big data
 
Android application development
Android application developmentAndroid application development
Android application development
 
Cyber crime
Cyber crimeCyber crime
Cyber crime
 

Kürzlich hochgeladen

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 

Kürzlich hochgeladen (20)

The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 

Collection framework (completenotes) zeeshan

  • 1. CollectionFramework Notes by Mr. Zeeshan CollectionFramework Definition: Collection is a java object that is used to group homogeneous and heterogeneous object’s without size limitation for carrying multiple objects at a time from one application to anther application among multiple layers of MVC architecture as method arguments and return type.  java.util package contains several classes to group/collect homogeneous and heterogeneous objects without size limitation. These classes are usually called collection framework classes. Limitation of Object type Arrays: 1) Arrays are fixed in size:  That is once we created an array there is no chance of increasing or decreasing the size based on our requirement.  Hence to use arrays concept compulsory we should know the size in advance, which mayn’t possible always 2) Arrays can hold only homogeneous data type elements. String[] s=new String[10]; s[0]=new String(); s[1]=new String(); s[2]="NIt"; we can overcome this limitation by using object type Arrays. Object o[]=new Object[10]; o[0]=new String(); o[1]=new String(); o[2]="NIt"; 3) Arrays concept isn’t implemented based on some data structure hence ready made method support isn’t available for arrays so for every requirement programmer is responsible to write the code.  To overcome the above limitations should go for collections.  Collections are growable in nature that is based on our requirement we can increase or decrease the size  Collections can hold both homogeneous and heterogeneous elements.  For every collection underlying data structure is available hence readymade method support is available for the every requirement. Differentiate Arrays and collections: Arrays Collection Arrays are fixed in size Collections are grow able in nature Arrays can hold only homogeneous data elements Collections can hold both homogeneous and heterogeneous elements With respect to memory arrays concept isn’t With respect to memory collections are recommended to use recommended to use. With respect to performance arrays are With respect to performance collection are not recommended to use recommended to use Arrays concept isn’t implemented based on some Every collection class is implemented based data structure hence readymade method support On some data structure; hence for every isn’t available requirement ready made method support is available. Arrays can hold both primitives and object type Collection can hold only object types but not primitives.
  • 2. CollectionFramework Notes by Mr. Zeeshan Collection framework: It defines several classes and interface which can be used to represent group of objects as single unit. All the collection classes and interfaces are present in java.util package. Sun developed many collection classes among them 15 are improtant,They are LinkedList HashSet HashMap ArrayList‘ LinkedHashSet LinkedHashMap Vector TreeSet TreeMap Stack Hashtable PriorityQueue Properties In addition to collection classes SUN also defined some helper classes They are Collections Scanner Locale Date Arrays StringTokenizer ResourceBundle Calendar Random Why the name collection framework? Framework :- Framework is a semi finished reusable application which provides Some common low level services and that can be customized accroding toour Requirements. Java.util package classes are provides some low level services with well defined Data structures to solve collection heterogeneous dynamic number of object’s As a single unit. Due to this reason java.util package classes are called collection f/w. All the collection classes are implementing from java.io.Serializable so the collection Object along with all it’s internal object’s can be stored in a local file system(OR) can Be sent across n/w to remote computer.Here Rule is Object’s stored in collection are Also should be serializable types to store collection in file. In How many formats can we collect Object’s? We can collect Objects in 2 ways 1) In Array Format—In this format object does not identity 2) In(key,value) pair formatIn this format object has identity
  • 3. CollectionFramework Notes by Mr. Zeeshan  Collection is an interface which can be used to represent a group of individual objects as a single entity, where as collections are a utility class to define several utility methods for collection object. In the above hierarchy, vector and stack classes are available since java 1.0, LinkedHashSet class is available since java 1.4 queue is available since java 5,and NavigableSet is available since java 6, and all other remaining classes and interfaces are available since java 1.2 version. Map hierarchy: Map hierarchy classes are used to collect elements in (key,value)pair format. In a map, keys should be unique and values can be duplicated. Each (key,value) is called an entry . In map by default entries are not sorted.
  • 4. CollectionFramework Notes by Mr. Zeeshan Collection interface:  If we want to represent a group of individual object as a single entity then we should go for collection.  These interfaces define the most common general methods which are applicable for any collection object.  Commonly used methods of Collection interface:  There are many methods declared in the Collection interface. They are as follows:  public boolean add(object element): is used to insert an element in this collection.  public boolean addAll(collection c):is used to insert the specifed collection elements in the invoking collection.  public boolean remove(object element):is used to delete an element from this collection.  public boolean removeAll(Collection c):is used to delete all the elements of specified collection from the invoking collection.  public boolean retainAll(Collection c):is used to delete all the elements of invoking collection except the specified collection.  public int size():return the total number of elements in the collection.  public void clear():removes the total no of element from the collection.  public boolean contains(object element):is used to search an element.  public boolean containsAll(collection c):is used to search the specified collection in this collection.  public Iterator iterator():returns an iterator. List interface:  It is the child interface of collection.  If we want to represent a group of individual objects where insertion order is preserved and duplicates objects are allowed, then we should go for list.  We can differentiate duplicate objects and we can maintain insertion order by using index, hence index placed very important role in list.  Commonly used mehtods of List Interface:
  • 5. CollectionFramework Notes by Mr. Zeeshan  public void add(int index,Object element);  public boolean addAll(int index,Collection c);  public object get(int Index position);  public object set(int index,Object element);  public object remove(int index);  public ListIterator listIterator();  public ListIterator listIterator(int i); ArrayList class: • ArrayList class extends AbstractList class and implements List interface. • ArrayList Object allowed duplicate elements. • ArrayList Object maintains insertion order. • ArrayList Object is not synchronized. • ArrayList Object accepts null value. Note :- Usually we can use collections to hold and transfer the data across network. To support this requirement every collection class already implements serializable and clonable interfaces. Array list classes and vector classes implements RandomAccess interface so that We can access any Random element with the same speed Hence if our frequent operation is retrieval operation ArrayList is the best choice. ArrayList is worest choice if you want to perform insertion(or)deletion in the middle .because internally several shift operations are required. Hierarchy of ArrayList class: ArrayList class Constructors :- 1) ArrayList():
  • 6. CollectionFramework Notes by Mr. Zeeshan Creates an empty arraylist obj with an intial capacity of 10(ten). If the ArrayList object reaches it max capacity a new ArrayList object will be created with NewCapacity = currentCapacity*3/2+1 2) ArrayList(int intialcapacity) Creates an empty arraylist obj with specified intial capacity. 3) ArrayList(Collection c) creates an equivalent ArrayList object for the given collection Listing 12.1 : Showing ArrayListDemo.java file import java.util.*; class ArrayListDemo{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add("Ravi"); al.add("Vijay"); al.add("Ravi");//duplicated String object al.add("Ajay"); al.add(null); System.out.println(al); } } Output: Vector class:  The underlying data structure is resizable array or growable array.  Insertion order is preserved  Duplication objects are allowed.  Null insertion possible  Implements Serializable, Consolable and RandomAceess interfaces.  Every method present in vector is synchronized and hence vector object is Thread Safe  Best suitable if our frequent operation is retrieval  Worst choice if our frequent operations are insertion or deletion in the middle.  Important methods of Vector class: SN Methods with Description 1 void add(int index, Object element) Inserts the specified element at the specified position in this Vector. 2 boolean add(Object o) Appends the specified element to the end of this Vector.
  • 7. CollectionFramework Notes by Mr. Zeeshan 3 boolean addAll(Collection c) Appends all of the elements in the specified Collection to the end of this Vector, in the order that they are returned by the specified Collection's Iterator. 4 boolean addAll(int index, Collection c) Inserts all of the elements in in the specified Collection into this Vector at the specified position. 5 void addElement(Object obj) Adds the specified component to the end of this vector, increasing its size by one. 6 int capacity() Returns the current capacity of this vector. 7 Object elementAt(int index) Returns the component at the specified index. 8 Enumeration elements() Returns an enumeration of the components of this vector. 9 Object get(int index) Returns the element at the specified position in this Vector. 10 int indexOf(Object elem) Searches for the first occurence of the given argument, testing for equality using the equals method. 11 int lastIndexOf(Object elem) Returns the index of the last occurrence of the specified object in this vector. 12 Object remove(int index) Removes the element at the specified position in this Vector. 13 boolean remove(Object o) Removes the first occurrence of the specified element in this Vector If the Vector does not contain the element, it is unchanged. 14 boolean removeAll(Collection c) Removes from this Vector all of its elements that are contained in the specified Collection. 15 void removeAllElements() Removes all components from this vector and sets its size to zero. 16 boolean removeElement(Object obj) Removes the first (lowest-indexed) occurrence of the argument from this vector.
  • 8. CollectionFramework Notes by Mr. Zeeshan 17 void removeElementAt(int index) removeElementAt(int index) 18 int size() Returns the number of components in this vector. 19 Object[] toArray() Returns an array containing all of the elements in this Vector in the correct order. 20 Object[] toArray(Object[] a) Returns an array containing all of the elements in this Vector in the correct order; the runtime type of the returned array is that of the specified array. 21 void trimToSize() Trims the capacity of this vector to be the vector's current size. ArrayList , Vector:  We should chose these two classes to store elements in indexed order and to retrieve them randomly, it means retrieving the element directly without retrieving (n-1) elements ,because these two classes are subclasses of RandomAccess interface.  Functionalities of these two classes: 1) Duplicate objects are allowed in indexed order 2) Heterogeneous objects are allowed 3) Insertion order is preserved 4) Implemented datastructure is growable array. 5) Null insertion is possible, more than one null is allowed. 6) Initial capacity is 10, incremental capacity is double for Vector and ArrayList used below formula(currentCapacity*3/2+1).whenever the collection object size reaches its max capacity, that class internal API creates new collection object based on its incremental capacity value. Then in new collection object old collection object elements are copied. Vector object is thread-safe: It means synchronized object so multiple threads cannot modify this object concurrently. It is best suitable in multithreaded model application to get desired result. But in single thread model application it gives poor performance, activity in single thread model application. To solve this performance issue in collection framework ArrayList class is given.  ArrayList object is not thread-safe it means it is not synchronized object. It is best suitable in multithreaded model application, also in multithreaded model application it you ensure there is not data corruption. Limitation: Inserting and removing elements in middle is costlier operation. Because for every insert operation elements must move to right and for every delete operation elements must move to left from that location.
  • 9. CollectionFramework Notes by Mr. Zeeshan To slove this issue we must choose LinkedList,It gives high Performance In inserting (OR) deleting elements in Middle. It Internally uses Linked List Data structure,so there will not be any data movements,instead we will have Only changing links ,and indexes The Example is showing Storing user-defined class objects into ArrayList import java.util.ArrayList; import java.util.Iterator; class Student { String name; int rollno; String course; int fee; Student(String name,int rollno,String course,int fee){ this.name=name; this.rollno=rollno; this.course=course; this.fee=fee; } public String toString(){ return "nName :"+name+ "nRoll No :"+rollno+ "nCourse :"+course+ "nFee :"+fee; } } class ArrayListExample{ public static void main(String[] args){ Student s1=new Student("sathish",123,"java",800); Student s2=new Student("venky",124,"c,c++",1000);
  • 10. CollectionFramework Notes by Mr. Zeeshan Student s3=new Student("3sha",125,"Oracle",500); ArrayList al=new ArrayList(); al.add(s1); al.add(s3); al.add(s2); Iterator itr=al.iterator(); while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st); } } } Output : The Example is showing Stroing the elements into Vector Object. import java.util.*;
  • 11. CollectionFramework Notes by Mr. Zeeshan public class VectorExample { public static void main(String args[]) { Vector vector = new Vector(); System.out.println("Initial size: " + vector.size()); System.out.println("Initial capacity: " +vector.capacity()); vector.addElement(new Integer(3)); vector.addElement(new Integer(4)); vector.addElement(new Integer(5)); vector.addElement(new Integer(6)); vector.addElement(new Double(6.35)); vector.addElement(new Double(7.98)); vector.addElement(new Integer(8)); vector.addElement(new Float(10.4)); vector.addElement(new Integer(11)); vector.add("java"); vector.add("c"); System.out.println("First element: " +vector.firstElement()); System.out.println("Last element: " +vector.lastElement()); System.out.println("Vector Capacity after adding 11 elements: "+vector.capacity()); System.out.println("Vector size after adding 11 elements: "+vector.size()); System.out.println("nElements in vector: " + vector); } } Output : LinkedList class: • LinkedList uses doubly linked list to store the elements. It extends the AbstractList class and implements List and Deque interfaces. • LinkedList object allows duplicate elements.
  • 12. CollectionFramework Notes by Mr. Zeeshan • LinkedList object maintains insertion order. • LinkedList Object is not synchronized. • LinkedList implements Serializable , clonable interfaces but not RandomAccess. • LinkedList best suitable our frequent operation is Insertion and deletion • in the middle. Linked List is Worst choice if our frequent operation is retrievable operation. Listening 12.6 showing storing the elements into LinkedList import java.util.*; class LinkedListDemo { public static void main(String args[]) { // create a linked list LinkedList ll = new LinkedList(); // add elements to the linked list ll.add("F"); ll.add("B"); ll.add("D"); ll.add("E"); ll.add("C"); ll.addLast("Z"); ll.addFirst("A"); ll.add(1, "A2"); System.out.println("Original contents of ll: " + ll); // remove elements from the linked list ll.remove("F"); ll.remove(2); System.out.println("Contents of ll after deletion: " + ll); // remove first and last elements ll.removeFirst(); ll.removeLast(); System.out.println("ll after deleting first and last: " + ll); // get and set a value Object val = ll.get(2); ll.set(2, (String) val + " Changed"); System.out.println("ll after change: " + ll); } } Output :-
  • 13. CollectionFramework Notes by Mr. Zeeshan Generics:- Introduction:- case(i):- once we created an array for a type we can add only that particular Type of objects. By mistake if we are trying to add any other type we will get C.E:- Hence we can give gurantee for the type of elements in array and Hence arrays are Type -safe. EX:- String s[]=new String[100]; s[0]="AAA"; s[1]="BBB"; s[2]=10;//C.T.E Hence we can give the gurantee that String array can contain only String Type of Objects. But Collections are not Type Safe,i.e we can't give the guarntee for the type of elements in collection. For Example if our programming requirement is to hold String objects and we can choose ArrayList,by mistake if you are trying to add any other type we won't get any compiletime Error. but there may be a chance of failing the app at runtime. EX:-
  • 14. CollectionFramework Notes by Mr. Zeeshan ArrayList l=new ArrayList(); l.add("sathish"); l.add("nit"); l.add((100); String s1=(String)l.set(0,"aaa"); String s2=(String)l.set(1,"sss"); String s3=(String)l.set(2,"ddd"); //R:Ex:--ClassCastException There is no gurantee the collection can hold Type of objects. Hence with respect to type, Arrays are Type safe to use. Where as Collection are not safe to use. case(ii):- ------- while reteriving Array elements it is not required to perform TypeCasting . we can assign Array Elements directly to the Corresponding Type variables. String[] s=new String[10]; s[0]="Sathish"; s[1]="nit"; String s=s[0];//sathish type casting is not required But while reterieving elements from collection compulsary we should perform Type casting. otherwise we will get CompileTimeError. Hence TypeCasting is the biggest headck in collections. to overcome the above problems of collections (Typesafety,Type casting) sun micro systems has introduced Generics concept in java 5 version. To Hold only String Type of Objects a Generic version of ArrayList can declare as follows ArrayList<String> l=new ArrayList<String>(); basetype parametertype for this arraylist we can hold only String type of objects, other wise we will get CE: 2)Hence generics can provide TypeSafty to collections .
  • 15. CollectionFramework Notes by Mr. Zeeshan At time of reterival it is not required to perform TypeCasting. Hence main objective of generics are 1) To provide TypeSafty for colletions 2) To reslove TypeCasting problem Conclusion--I:- --------------- EX:- -- 1) AL<String> l=new AL<String>();//valid 2) Al<Object> l=new AL<String>();//C.T.E:- conclusion-II:- ------------- At the type parameter we can use any class (or) Interface name and we can't provide primitive Type. 1)AL<Integer> l=new AL<Integer>(); 2) AL<int> l=new AL<int> ();//C.T.E:- Generic class:- --------------- non generic version of ArrayList class is declared as follows class ArrayList { add(Object o) Object get(int index) } the add() method can take object as argument . Hence we can add any type of object to ArrayList . Due to this we are not getting typesafty. The return type of get(-)method is object hence at the time of reterival compulsary we should perform type casting. But from 1.5 version a generic version of ArrayList class is define as follows. class ArrayList<T>{ add(T t) T get(int index) }
  • 16. CollectionFramework Notes by Mr. Zeeshan Based on our requirement "T" will be replaced with corresponding Type. -->Through Generics we can associate type parameter for the class such type of parametrized classes are called Generic classes. --> we can create our own Generic classes also Ex:- class Bank<T> { } Bank<Icici> b=new Bank<Icici>(); Bounded Types:- --------------------- We can bound the type parameters for a particular rangesuch types are called bounded types. Ex:- 1) class Test<T> {//UnBoundedType } as the type parameter we can pass any type There are no restrictions. Hence it is unbound type. Ex:2) class Test<T extends X> //x is class/interface { } If X is a class then as the type parameter we can pass either X type (or) it's sub classes. If X is an interface then as the type parameter we can pass either Xtype (or) it's implementations classes.
  • 17. CollectionFramework Notes by Mr. Zeeshan Ex:- class Test<T extends Number>{ } Test<Integer> t=new Test<Integer>(); Test<String> t=new Test<String>();//C.T.E we can bound the type parameters only by using extends keyword. and we cannot bound by using implements and super keywords. Creation of our own generics:- ------- -------------------------------- class Test<T>{ T obj; Test(T obj) { this.obj=obj; } public void show(){ System.out.println(" The Type of Obj is :"+obj.getClass().getName()); } public T getObj(){ return obj; } } class GenericsDemo{ public static void main(String[] args) { Test<String> g1=new Test<String>("Sathish"); g1.show();//the type obj is java.lang.String System.out.println(g1.getObj());//sathish Test<Integer> g2=new Test<Integer>(10); g2.show();//java.lang.Integer System.out.println(g2.getObj());//10 Test<Double> g3=new Test<Double>(10.55); g3.show();//java.lang.Double System.out.println(g3.getObj());//10.55 } }
  • 18. CollectionFramework Notes by Mr. Zeeshan Type Inference for Generic instance creation (or) Diamond Syntax:- --------------- You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (< >) . This pair of angle brackets is called the diamond. For example, consider the following variable declarations: ArrayList<String> al=new ArrayList<>();// valid from java 7 ArrayList<Integer> al=new ArrayList<>();// valid from java 7 Note: Collections are not Type Safe, i,e we can't give the guarantee for the type of elements in collection. While retrieving elements from collection compulsory we should perform Type casting. Otherwise we will get CompileTimeError. To overcome the above problems of collections (Typesafety , Type casting) Generics are introduced in JSE 5.0 version. Hence main objective of generics are 1) To provide TypeSafty for C olletions 2) To reslove TypeCasting Problem The 3 cursor’s of java:  If we want to retrieve objects one by one from the collection then we should go for cursor.  There are three cursors are available in java. 1) Enumaration 2) Iterator 3) ListIterator Enumaration:  We can use enumeration object to get the objects one by one from legacy collection objects.  We can create enumeration object by using elements method Enumaration e=v.elements();  Enumeration interface defines the following two methods. 1) public boolean hasMoreElements(); 2) public object nextElement(); Ex:
  • 19. CollectionFramework Notes by Mr. Zeeshan import java.util.*; class EnumarationDemo {public static void main(String[] args) { Vector v=new Vector(); for (int i = 0; i < 10; i++) { v.addElement(i); } System.out.println(v); Enumeration e=v.elements(); while(e.hasMoreElements()) { Integer i=(Integer)e.nextElement(); if(i%2==0) System.out.println(i); } System.out.println(); System.out.println(v); } } Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0 2 4 6 8 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Limitations of Enumeration:  Enumeration concept is applicable only for legacy classes.  By using Enumeration we can get only read capability and we can’t perform remove operation. To overcome the above limitations we should go for the Iterator. Iterator:  We can use Iterator for any collection object to get objects one by one from the Collection.  While iterating objects by Iterator, we can perform remove operation in addition to read operation.  We can get Iterator object by using iterator() method on collection interface. public Iterator iterator(); Iterator itr=c.iterator(); here c is any collection Object.  Iterator interface defines the following three methods. 1) Public boolean hasNext(); 2) Public object next(); 3) Public void remove(); Exa:let’s developing below program above Iterator methods. import java.util.*; class EnumarationDemo { public static void main(String[] args) { ArrayList al=new ArrayList(); for (int i = 0; i < 10; i++) {
  • 20. CollectionFramework Notes by Mr. Zeeshan al.add(i); } System.out.println(al); Iterator i=al.iterator(); while(i.hasNext()) { Integer ele=(Integer)i.next(); if(ele%2==0) System.out.println(ele); else i.remove(); } System.out.println(); System.out.println(al); } } Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0 2 4 6 8 [0, 2, 4, 6, 8] Limitaitions of Iterator: 1) By using Enumeration and Iterator, we can always move towards forward direction and we can’t move the backward direction, that is these are single direction cursors. 2) By using Iterator, we can perform only read and remove of operations and we cannot perform replace operation on the addition of new objects. To overcome above limitations we should go for ListIterator. ListIterator: 1) It is the child interface of iterator. By using ListIterator we can move either to the forward direction or to the backward direction. 2) It is a bidirectional cursor. 3) While iterating objects by ListIterator then we can perform replacement and addition of new objects in addition to read and remove operations. 4) We can create ListIterator by using ListIterator() method of List(I). public ListIterator listIterator() ListIteator ltr=l.listIterator()--> here any list object. ex: Let’s understand above concept to develop below program. import java.util.*; class ListIteratorDemo { public static void main(String[] args) { LinkedList l=new LinkedList(); l.add("ramu"); l.add("raju"); l.add("sai"); l.add("sairam"); l.add("vijay"); System.out.println(l);
  • 21. CollectionFramework Notes by Mr. Zeeshan ListIterator li=l.listIterator(); while(li.hasNext()) {String s=(String)li.next(); if(s.equals("ramu")) { li.remove(); System.out.println(s); System.out.println(); } System.out.println(s); } } } Note:The most powerful cursor is ListIterator but its limitation is it is applicable only for List object. Set  It is the child interface of collection.  If we want to represent a group of individual objects where duplicates aren’t allowed and insertion order isn’t preserved then we should go for Set.  Set Interface doesn’t contain any new methods we have to use only collection interface methods HashSet:  The underlying data structure is “Hashtable”.  Insertion order is n’t follows.  Duplicate objects are n’t allowed and if we are trying to insert duplicate object we don’t get any compile time or runtime exceptions, simple add() method returns false.  Heterogeneous objects are allowed.  null insertion is possible  HashSet implements seriablizable and cloneable interface.  If our frequent operation is SearchOperation then HashSet is best choice. Constructor: 1) HashSet h=new HashSet(); Creates an empty HashSet object with the default initial capacity is 16 and default fillratio is “.75” 2) HashSet h=new HashSet(int initialcapacity); Creates an empty HashSet object with the specified initial capacity and default fillratio 0.75%. 3) HashSet h=new HashSet(int initialcapacity,float fillratio); 4) HashSet h=new HashSet(Collection c);
  • 22. CollectionFramework Notes by Mr. Zeeshan Ex:write a simple program using HashSet. import java.util.HashSet; public class HashSetDemo { public static void main(String[] args) { HashSet hs=new HashSet(); hs.add("a"); hs.add("b"); hs.add("c"); hs.add("d"); hs.add(null); hs.add(10); hs.add(null);//false System.out.println(hs); } } Output: [null, d, b, c, a, 10] Note :- refer HashSetDemo1,HashSetDemo2 example programms in folder 1) public native int hashCode():- ------------------------------------------ to get the hashCode of the object we can call hashCode(). we can override the hashCode() in the user-defined classes to create the Our own hashCodes by using object state. JVM will always uses these HashCodes while saving the Objects into Hashtable,HashMap and HashSet. equals():- ---------- equals() method is given to compare two objects for their equality. In java we can compare objetcs in two ways either. 1. By using Objects reference or 2.By using Objects state. If two objects of a class are said to be equal only if their reference or state is equal. we have to compare the objects either by 1. using == operator -->It always compares objects with their references. 2. using equals() method-->It always objects based on it's implementation. equals() method implementation inside object class. -------------------------------------------------------------- In object class this method is implemented to compare two objects with their references,as shown below public boolean equals(Object obj){ return(this==obj); } this method return true if the current object reference is equals to argument object reference,else it return false.
  • 23. CollectionFramework Notes by Mr. Zeeshan If we want to compare two objects with state we must override this method in sub class. contract between equals() and hashCode():- if the equals() method return true by comparing two objects,then hashCode of the both objects must be same. If it returns false ,the hashCode of the both objects may(or) may not be same. Difference b/w equals() and == == operator will only compare reference of the Objects. Real world object's must be compared with thieir state. it is not possible to override the== operator. equals() is given by the sun to compare the object’s equals() will compares the Object’s based on the implementation . in object class equals() was implemented to compare the object’s with reference. If we want to compares the object’s with the state we can Override the equals() method. Note :- Java Object's identity is called hashcode.It is a 32 bit random integer number created by jvm for every object. Each object will have a unique identity. The hashcode of the object can be retrieved by using a method "hashcode()." Developer can also generate hashcode of an object based on the state of that object by overriding hashCode() In this case ,if state is changed ,automatically hashCode will be changed . Note :- JVM generated hashCode will not be changed if object state is changed , HashCode is used when object is stored in HashTable . LinkedHashSet:  It is the child class of HashSet  It is exactly same as HashSet(including constructor and method) except the following differences. HashSet LinkedHashSet The underlying data structure is Hashtable The underlying data structructure is the combination of the Hashtable and LinkedList. Insertion order isn’t preserved Insertion order is preserved. Introduced in 1.2 version Introduced in 1.4 version. Ex:write a sample program using LinkedHashSet
  • 24. CollectionFramework Notes by Mr. Zeeshan import java.util.HashSet; import java.util.LinkedHashSet; public class LinkedHashSetDemo { public static void main(String[] args) { LinkedHashSet hs=new LinkedHashSet(); hs.add("a"); hs.add("b"); hs.add("c"); hs.add("d"); hs.add(null); hs.add(10); hs.add(null);//false System.out.println(hs); } } Output: [a, b, c, d, null, 10] sortedSet:  It is the child interface of Set  If we want to represent a group of individual objects according to some sorting order without duplicates, then we should go fro SortedSet.  SortedSet interface defines the following methods. 1) Object first() Return first element of the sortedSet. 2) Object last()returns last element of the SortedSet. 3) SortedSet headset(Object ob) Retruns sortedset whose elements are less than ob. 4) SortedSet tailSet(Object ob) Retruns sortedset whose elements are greater than ob. 5) SortedSet subset(object obj1,object obj2) Return sortedSet whose elements are greater then or equal to obj1 and less than obje2. 6) Comparator comparator() Return comparator obj , which describe underlying sorting technique. TreeSet:  Underlying data structure is BalancedTree  Duplicate objects aren’t allowed  Insertion order isn’t preserved and it is based on the some SortingOrder.  Null insertion is possible (only once) when it is the first element.  Heterogeneous objects aren’t allowed and if we are trying to insert the heterogeneous objects we will get the RuntimeeException saying ClassCastException. Constructor: 1) TreeSet t=new TreeSet(); If crates an empty TreesSet object wher all objects will be inserted according to Natural sorting order. 2) TreeSet t=new TreeSet(Comparator c); Creates an empty TreeSet object where all objects will be inserted according to customized Sorting order, which is the described by comparator object. 3) TreeSet t=new TreeSet(SortedSet c); 4) TreeSet t=new TreeSet(Collection c); Null acceptance:
  • 25. CollectionFramework Notes by Mr. Zeeshan For the nonempty TreeSet, if we are trying to inserting the null and we will get NullpointerException  For the empty TreeSet, as the first element null insertion is possible. But after inserting that null if we are trying to insert any other element then we will get NullpointerException. From java 7 empty tree set also not allows the null value. Refer the Example Programms in the ClassRoom Programms Folder Difference between comparable and comparator interfaces: Comparable interface:  Comparable interface present in java.lang package and it contains only one method that is compareTo() public int compareTo(Object obj) obj1.compareTo(obj2)here return “-v” when obj1 has to place before obj2.return “+v”if and only obj1 has to place after obj2.return “0” if and only obj1 and obj2 both are equal.  Comparable used to specify natural sorting order internally jvm will call compareTo () method to place objects into the TreeSet. import java.util.TreeSet; class SetClassDemo { public static void main(String[] args) { TreeSet ts=new TreeSet(); ts.add("a"); ts.add("z"); ts.add("c"); System.out.println(ts);} } Output: acz Below diagram how to check internal in compareTo() method:
  • 26. CollectionFramework Notes by Mr. Zeeshan  Comparable is meant for default natural sorting order where as comparator is meant for customized sorting order. Comparator(I):  This interface present in java.util package and contains the following two methods. public int compare(Object obj1,Object obj2) public Boolean equals(Object obj)  Whenever we are implementing comparator interface compulsory we should provide implementation for compare () method.  Implementing equals () method is optional because it is already available in every java class from object class. Ex: Write a program using comparable interface. import java.util.TreeSet; class Address implements Comparable {int x; Address() {} Address(int x) { this.x=x; } public int compareTo(Object obj) { Address a=(Address)obj; return a.x=this.x; } public String toString() { return ""+x; } } import java.util.TreeSet; public class AddingCustomobjects { public static void main(String[] args) { TreeSet ts=new TreeSet(); ts.add(new Address()); ts.add(new Address(20)); ts.add(new Address()); ts.add(new Address(5)); ts.add(new Address(30)); ts.add(new Address(20)); ts.add(new Address()); System.out.println(ts.size()); System.out.println(ts); } } Output: 5 [5, 0, 20, 20, 20] Ex#2: Write a program using comparator interface. import java.util.Comparator; import java.util.TreeSet; class StringComparator implements Comparator {
  • 27. CollectionFramework Notes by Mr. Zeeshan public int compare(Object ob1, Object ob2) { String astr,bstr; astr=(String)ob1; bstr=(String)ob2; return bstr.compareTo(astr); } } class ComparatorDemo{ public static void main(String[] args) { TreeSet ts=new TreeSet(); ts.add("A"); ts.add("B"); ts.add("C"); ts.add("N"); System.out.println("ts object with default comparator"+ts); TreeSet tsc=new TreeSet(new StringComparator()); tsc.add("A"); tsc.add("B"); tsc.add("C"); tsc.add("N"); tsc.add("z"); System.out.println("ts object with custom comparator"+tsc); } } Output: ts object with default comparator[A, B, C, N] ts object with custom comparator[z, N, C, B, A] Remaining example lab exercise ex#2. Comparable v/s Comparator:  For predefined comparable classes like String default natural Sorting order is already available. If we aren’t satisfied with that natural sorting order we can define own sorting by Comparator object.  For predefined non Comparable classes like StringBuffer the default natural sorting order isn’t already available, we can define our own sorting by Comparator.  For our own classes the person who is writing the class he can define default natural sorting order by implementing comparable interface.  The person who is using our own classes, if he isn’t satisfied with default natural sorting order, then he can define his own sorting by using comparator object. Comparable Comparator  This interface meant for default natural sorting order  This interface meant for the customized sorting order  This interface present in default java.lang package This interface present in the java.util package.
  • 28. CollectionFramework Notes by Mr. Zeeshan  It defines only one method compareTo() It defines two methods compare() equals() Sorting class, all wrapper classes implements Comparable interface The only implemented classes of comparator interface are  Collator  RuleBasedCollator. Conclusion: comparison table of Set implemented class property HashSet LinkedHashSet TreeSet  Underlying ofthe datastructure Hashtable Hashtable+likedList BlancedTree  Insertion order Not preserved Preserved Not preserved  Sorting order Not applicable Not applicable applicable Heterogeneous object allowed Allowed Not allowed Duplicate object Not allowed Not allowed Not allowed Null acceptance allowed Allowed As the first element null is allowed. In all reaming case we will get NPE. Map interface:  Map is n’t child interface of Collection.  If we want to represent a group of objects as key,value pairs then we should go for Map.  Both key and value are objects only.  Duplicate keys aren’t allowed but the values can be duplicated.  In map Each key,value pair is called as one entry.
  • 29. CollectionFramework Notes by Mr. Zeeshan Map interface methods: 1) Object put(Object key,Object value) to insert one key and value pair (Entry) to the Map.  If the specified key is already available then old value is replaced with new value and the old value will be return. 2) void putAll(Map m) to insert a group of key,value pairs 3) Object get(Object key) to get value associated with specified key. 4) boolean containsKey(Object key) used to check the the specified key is available (OR) not 5) boolean containsValue(Object value) used to check the the specified value is available (OR) not 6) boolean isEmpty() used to to check the map is empty or not. 7) int size()used to get the size of the map object 8) void clear()  used to clear the map object 9) Object remove(Object key)  used to remove entry based on the specified key. 10) Set keyset()this method returns all the key’s of a map object 11) Collection values()this method return’s all the alues of the map 12) Set entrySet()this method returns the all the entries of the map Entry interface: Entry is an Inner interface of Map Each key,value pair is called as one entry .Hence map is considered as a group of Entries. Without existing map object there is no chance of existing entry object. Methods of Entry interface:- public Object getKey() public Object getValue()  HashMap:  The underlying datastructure is Hashtable.  Insertion order is n’t follows.  Duplicate key’s aren’t allowed but the values can be duplicated.  Heterogeneous objects are allowed for both keys and values
  • 30. CollectionFramework Notes by Mr. Zeeshan  Null keys are allowed for key (only once)and for the values (any no of times) HashMap Hashtable no method is synchronized every method is synchronized HashMap object can be accessed by multiple threads and hence it isn’t Thread safe. Hashtable object can be accessed by only one thread at a time and hence it is thread safe. Relatively performance is high. Relatively performance is low. We can insert null for both key and values Null isn’t allowed for both key and values otherwise we will get NullPointerEx Introduced in 1.2 version It is non legacy. Introduced in 1.0 version and it is legacy. Constructor: 1) HashMap m=new HashMap(); Creates an empty hashmap() object with default initial capacity is 16 and default fillratio is .75 2) HashMap m=new HashMap(int initialcapacity); 3) HashMap m=new HashMap(int initialcapacity,float fillratio); 4) HashMap m=new HashMap(Map m); Refer the examples in the classroomExampleProgramms folder LinkedHashMap:  It is exactly same as HashMap except the following differences.  The underlying datastructure is Hashtable,the underlying datastructure is a combination of Hashtable +LinkedList.  In LinkedHashMap Insertion is presereved ,but in the HashMap Insertion Order is not preserved IdentityHashMap : Identity HashMap is the Implemented class of Map interface.Identity HashMap is same as HashMap Except the following differencs. For identifying duplicate keys In the case of HashMap JVM Uses equals() method, Where as In the case of Identity HashMap JVM Uses the “==” (double equal) operator. WeakHashMap:- WeakHashMap is the Implemented class of Map interface.WeakHashMap is same as HashMap Except the following differences.
  • 31. CollectionFramework Notes by Mr. Zeeshan • In case of HashMap an Object is not eligible for garbage collection if it is associated with HashMap . Even though it doesnt have any external references. i.e, HashMap dominates garbage collector. • But in case of WeakHashMap ,if an Object is not having any external references then it is always eligible for garabage collector even though it is associated with WeakHashMap . i.e, garbage collector dominates WeakHashMap Sorted Map interface : • The Collection Framework provides a special Map interface for maintaining elements in a sorted order called SortedMap . SortedMap is the sub interface of Map. • If we want to represent a group of key value pairs according to some sorting order of keys then we should go for Sorted Map. • In Sorted Map we can perform sorting only based on the keys but not values. SortedMap interface Specifc Methods Object firstKey() object lastKey() SortedMap headMap(Object key) SortedMap tailMap(Object key) Sotredmap subMap(Object key1,Object key2) Comparator comparator() Note : Working with a SortedMap is just similar to a SortedSet except, the sort is done on the map keys. NavigableMap The java.util.NavigableMap(java 1.6) interface is a subinterface of the java.util.SortedMap interface. It has a few extensions to the SortedSet which makes it possible to navigate the map. I will take a closer look at these navigation methods in this text. The java.util package only has one implementation of the NavigableMap interface: java.util.TreeMap. Here is a list of the topics covered in this text: 1. descendingKeySet() and descendingMap() 2. headMap(), tailMap() and subMap() 3. ceilingKey(), floorKey(), higherKey() and lowerKey() 4. ceilingEntry(), floorEntry(), higherEntry() and lowerEntry() 5. pollFirstEntry() and pollLastEntry() 6. descendingKeySet() and descendingMap() : The first interesting navigation methods are the descendingKeySet() and descendingMap() methods. The descendingKeySet() method returns a NavigableSet in which the order of the elements is reversed compared to the original key set. The returned "view" is backed by the original NavigableSet ket set, so changes to the descending set are also reflected in the original set.
  • 32. CollectionFramework Notes by Mr. Zeeshan However, you should not remove elements directly from the key set. Use the Map.remove() method instead. Here is a simple example: NavigableSet reverse = map.descendingKeySet(); The descendingMap() method returns a NavigableMap which is a view of the original Map. The order of the elements in this view map is reverse of the order of the original map. Being a view of the original map, any changes to this view is also reflected in the original map. Here is a simple example: NavigableMap descending = map.descendingMap(); headMap(), tailMap() and subMap() : The headMap() method returns a view of the original NavigableMap which only contains elements that are "less than" the given element. Here is an example: NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //this headmap1 will contain "1" and "2" SortedMap headmap1 = original.headMap("3"); //this headmap2 will contain "1", "2", and "3" because "inclusive"=true NavigableMap headmap2 = original.headMap("3", true); The tailMap() method works the same way, except it returns all elements that are higher than the given parameter element. The subMap() allows you to pass two parameters demarcating the boundaries of the view map to return. Here is an example:
  • 33. CollectionFramework Notes by Mr. Zeeshan NavigableMap original = new TreeMap(); original.put("1", "1"); original.add("2", "2"); original.add("3", "3"); original.add("4", "4"); original.add("5", "5"); //this submap1 will contain "3", "3" SortedMap submap1 = original.subMap("2", "4"); //this submap2 will contain ("2", "2") ("3", "3") and ("4", "4") because // fromInclusive=true, and toInclusive=true NavigableMap submap2 = original.subMap("2", true, "4", true); ceilingKey(), floorKey(), higherKey() and lowerKey() : The ceilingKey() method returns the least (smallest) key in this map that is greater than or equal to the element passed as parameter to the ceilingKey() method. Here is an example: NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //ceilingKey will be "2". Object ceilingKey = original.ceilingKey("2"); //floorKey will be "2". Object floorKey = original.floorKey("2"); The floorKey() method does the opposite of ceilingKey() The higherKey() method returns the least (smallest) element in this map that is greater than (not equal too) the element passed as parameter to the higherKey() method. Here is an example: NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //higherKey will be "3". Object higherKey = original.higherKey("2"); //lowerKey will be "1" Object lowerKey = original.lowerKey("2"); The lowerKey() method does the opposite of the higherKey() method. celingEntry(), floorEntry(), higherEntry(), lowerEntry() :
  • 34. CollectionFramework Notes by Mr. Zeeshan The NavigableMap also has methods to get the entry for a given key, rather than the key itself. These methods behave like the ceilingKey() etc. methods, except they return an Map.Entry instead of the key object itself. A Map.Entry maps a single key to a single value. Here is a simple example. For more details, check out the JavaDoc. NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //higherEntry will be ("3", "3"). Map.Entry higherEntry = original.higherEntry("2"); //lowerEntry will be ("1", "1") Map.Entry lowerEntry = original.lowerEntry("2"); pollFirstEntry() and pollLastEntry() : The pollFirstEntry() method returns and removes the "first" entry (key + value) in the NavigableMap or null if the map is empty. The pollLastEntry() returns and removes the "last" element in the map or null if the map is empty. "First" means smallest element according to the sort order of the keys. "Last" means largest key according to the element sorting order of the map. Here are two examples: NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //first is ("1", "1") Map.Entry first = original.pollFirstEntry(); //last is ("3", "3") Map.Entry last = original.pollLastEntry(); TreeMap:  The underlying datastructure is RED-BLACK Tree  Duplicate keys aren’t allowed but the values can be duplicated.  Insertion order isn’t preserved and all entries will be inserted according to some sorting order of keys  If we are depending on default natural sorting order then compulsory keys should be homogeneous and comparable otherwise we will get ClassCastException. But if we are defining our own sorting by comparator then the keys need n’t be comparable and homogeneous.  There are no restication for values, they can be heterogeneous and non comparable.  Upto java 6 version For empty TreeMap as first entry with null key is allowed but after inserting the entry .if we are trying to insert any other entry we will get “NullpointerException“.  Upto java 6 version For non empty TreeMap if we are trying to insert an entry with null key then we will get NPE.
  • 35. CollectionFramework Notes by Mr. Zeeshan  But From java 7 version null key’s are not allowed .  There are no restrictions for null values. Constructors: 1) TreeMap tm=new TreeMap() For default natural sorting order. 2) TreeMap tm=new TreeMap(Comparator c) For customized sorting order. 3) TreeMap tm=new TreeMap(SortedMap c) Interconversion of sortedMap 4) TreeMap tm=new TreeMap(Map c) Interconversion between Map. Hashtable:  Underlying datastructure for Hashtable is Hashtable  Duplicate keys aren’t allowed but values can be duplicated  Insertion order isn’t preserved and it is based on Hashcode of the keys.  Heterogeneous objects are allowed for both keys and values.  Null insertion isn’t possible fore both key and value otherwise we will get NPE.  Every method present in Hashtable is synchronized and hence Hashtable object is Threadsafe. Constructor: 1) Hashtable h =new Hashtable();  Creates an empty Hashtable object with default initial capacity “11” and default fillration .75. 2) Hashtable h =new Hashtable(int initialcapacity); 3) Hashtable h =new Hashtable(int initialcapacity,float fillratio); 4) Hashtable h =new Hashtable(Map); HashtableDemo.java import java.util.Enumeration; import java.util.Hashtable; import java.util.Set; public class HashtableDemo { public static void main(String args[]) { // Creating Hashtable for example Hashtable companies = new Hashtable(); // to put object into Hashtable companies.put("Google", "United States"); companies.put("Nokia", "Finland"); companies.put("Sony", "Japan"); // to get Object from Hashtable companies.get("Google"); // Use containsKey(Object) method to check if an Object exits as key in // hashtable System.out.println("Does hashtable contains Google as key: " + companies.containsKey("Google")); /* just like containsKey(), containsValue returns true if hashtable contains specified object as value*/
  • 36. CollectionFramework Notes by Mr. Zeeshan System.out.println("Does hashtable contains Japan as value: " + companies.containsValue("Japan")); // Hashtable elements() return enumeration of all hashtable values Enumeration enumeration = companies.elements(); while (enumeration.hasMoreElements()) { System.out.println("hashtable values: " + enumeration.nextElement()); } // use size() method to find size of hashtable in Java System.out.println("Size of hashtable in Java: " + companies.size()); // use keySet() method to get a Set of all the keys of hashtable Set hashtableKeys = companies.keySet(); // get enumeration of all keys by using method keys() Enumeration hashtableKeysEnum = companies.keys(); } } Output : Properties:  In our program if any thing which changes frequently( like username, password etc) are never recommended to hardcode those values in our java program because for every change we have to recompile ,rebuilt, redeploy application and sometimes we have to restart server is also required which creates a big business impact to the client.  Such type of values we have to place inside the properties file and we have to read those values from the properties file into the java application.  The main advantage of this application is if any change in properties file to reflect those changes just redeployment is enough which won’t create any business object to hold properties from the properties file.  Properties class is the child class of the Hashtable and both key and values should be String type. Constructor: 1) Properties p =new Properties(); Methods: 1) String getProperty(String pname); Return the value associated with specified property. 2) String setProperty(string pname,string pvalue) To add a new property 3) Enumaration propertyNames(); 4) Void load (InputStream is) To load properties from properties file into java properties object. 5) void store(OutputStream os,String comment) to store the properties from java application into Properties file. Ex:
  • 37. CollectionFramework Notes by Mr. Zeeshan import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; class propertiesDemo { public static void main(String[] args) throws IOException { Properties p=new Properties(); FileInputStream fis=new FileInputStream("src/nit.properties"); p.load(fis); System.out.println(p); String s=p.getProperty("nit"); System.out.println(s); p.setProperty("nit", "9090"); FileOutputStream fos=new FileOutputStream("abc.properties"); p.store(fos, "update is successfully"); } } Output abc.properties #update is successfully #Sat Aug 24 21:00:20 GMT+05:30 2013 laxman=core java nit=9090 java.util.Collections: Collections class provides static methods for sorting the elements of collection .If collection elements are of Set type, directly we can use TreeSet. But We cannot sort the elements of List .So Collections class provides methods for sorting the elements of List type elements. Method of Collections class for sorting List elements public void sort(List list): is used to sort the elements of List. List elements must be of Comparable type. Note: String class and Wrapper classes implements the Comparable interface.So if you store the objects of string or wrapper classes, it will be Comparable. public void sort(List list,Comparator c): is used to sort the elements of List by the given comparator. The following example showing how to Sort the elements of List that contains user-defined class objects .
  • 38. CollectionFramework Notes by Mr. Zeeshan import java.util.*; class Student implements Comparable{ int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } public String toString(){ return "name = "+name+" rollno = "+rollno+" age = "+age+"n"; } public int compareTo(Object obj){ Student st=(Student)obj; if(age==st.age) return 0; else if(age>st.age) return 1; else return -1; } } class ArrayListSortDemo{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(new Student(101,"Vijay",23)); al.add(new Student(106,"Ajay",27)); al.add(new Student(105,"Jai",21)); System.out.println("Before Sorting :"); System.out.println(al); Collections.sort(al); System.out.println("After Sorting :"); System.out.println(al); } } Output :
  • 39. CollectionFramework Notes by Mr. Zeeshan Student class contains three fields rollno, name and age and a parameterized constructor. class Student { int rollno; String name; int age; Student(int rollno,String name,int age){ this.rollno=rollno; this.name=name; this.age=age; } public String toString(){ return "name = "+name+" rollno = "+rollno+" age = "+age+"n"; } } The following example showing AgeComparator.java AgeComparator class defines comparison logic based on the age. If age of first object is greater than the second, we are returning positive value, it can be any one such as
  • 40. CollectionFramework Notes by Mr. Zeeshan 1, 2 , 10 etc. If age of first object is less than the second object, we are returning negative value, it can be any negative value and if age of both objects are equal, we are returning 0. import java.util.Comparator; class AgeComparator implements Comparator{ public int compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; if(s1.age==s2.age) return 0; else if(s1.age>s2.age) return 1; else return -1; } } The following example showing NameComparator.java NameComparator class provides comparison logic based on the name. In such case, we are using the compareTo() method of String class, which internally provides the comparison logic. import java.util.Comparator; class NameComparator implements Comparator{ public int compare(Object o1,Object o2){ Student s1=(Student)o1; Student s2=(Student)o2; return s1.name.compareTo(s2.name); } }
  • 41. CollectionFramework Notes by Mr. Zeeshan The following example showing ArrayListDemo.java In ArrayList class, we are printing the objects values by sorting on the basis of name and age. import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; class ArrayListDemo{ public static void main(String args[]){ ArrayList al=new ArrayList(); al.add(new Student(101,"Vijay",23)); al.add(new Student(106,"Ajay",27)); al.add(new Student(105,"Jai",21)); System.out.println("Sorting by Name..."); Collections.sort(al,new NameComparator()); Iterator itr=al.iterator(); while(itr.hasNext()){ Student st=(Student)itr.next(); System.out.println(st); } System.out.println("sorting by age..."); Collections.sort(al,new AgeComparator()); Iterator itr2=al.iterator(); while(itr2.hasNext()){ Student st=(Student)itr2.next(); System.out.println(st); } } }
  • 42. CollectionFramework Notes by Mr. Zeeshan Output : Queue interface:  It is the child interface of collection.  If we want to represent a group of individual objects prior to processing then we should go for queue interface.  From 1.5 versions onwards LinkedList also implements from queue interface.  Usually queue first in first out order (fifo) but based on our requirement we can implement our own order also.  LinkedList based implementation of queue always follows fifo only. Queue interface specific methods: 1) Boolean offer(Object o) to insert an object into the queue. 2) Object peek() it returns head element of the queue , if queue is empty then this method returns null. 3) Object element () it returns head element of the queue and if Queue is empty then we will get the runtime exception saying NoSuchElementException. 4) Object poll() to remove and return head element of the queue and if the queue is empty then we will get null. 5) Object remove() to remove and return head element of the queue and if the queue is empty then we will get RuntimeException. priorityQueue:  It is a datastructure where all objects will be arranged according to some priority , prior to processing.
  • 43. CollectionFramework Notes by Mr. Zeeshan  The priority order can be either default natural sorting order or customized sorting order specified comparator object.  Duplicate objects aren’t allowed.  Null insertion isn’t possible even as the first element also.  If we are depending on default natural sorting order then the objects should be homogeneous and comparable otherwise we will get ClassCastException.  If we are defining our own sorting then the objects needn’t be comparable and homogeneous. Constructors: 1) New PriotityQueue()creates an empty priorityQueue with default initial capacity 11 and sorting order is default natural sorting order. 2) new PriorityQueue(int initialcapacity) 3) new priorityQueue(int initialcapacity, comparator c); 4) new PriorityQueue(SortedSet ss) 5) new PriorityQueue(int initialcapacity) 6) new PriorityQueue(collection c) ex: let’s write a program above concept. import java.util.PriorityQueue; public class priorityQueueDemo { public static void main(String[] args) { PriorityQueue pq=new PriorityQueue(); for (int i = 0; i < 10; i++) { pq.offer(i); } System.out.println(pq); System.out.println(pq.poll()); System.out.println(pq); } } Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 0 [1, 3, 2, 7, 4, 5, 6, 9, 8] NavigableSet:  It is the child interface of sortedSet.  This interface defines the following methods which are useful for navigation purposes. Methods: 1) floor(e)  It return highest element which is <=e 2) lower(e)  It returns element which is <e. 3) ceiling(e) it returns lowest element which is >=e. 4) higher(e) it returns lowest element which is >e. 5) pollFirst() remove and return first element 6) pollLast() remove and return last element 7) descendingSet() it returns NavigableSet in revers order.
  • 44. CollectionFramework Notes by Mr. Zeeshan Ex: import java.util.Comparator; import java.util.PriorityQueue; import java.util.TreeSet; class NavigatableSetDemo { public static void main(String[] args) { TreeSet ts=new TreeSet(); ts.add(1000); ts.add(2000); ts.add(3000); ts.add(5000); System.out.println(ts); } } Output: [1000, 2000, 3000, 5000]