We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 138
Need Of Collections
{an array is an indexed Collection of fixed number of homogeneous data elements.
The Main advantage of Arrays is we can represent multiple values witha single variable
So that reusability of the code will be improved.
Limitations of Object type Arrays:
Arrays are fixed in size i.e. once we created an array with some size there is no chance of increasing or decreasing it's size based on
‘ur requirement. Hence to use arrays compulsory we should know the size in advance which may not possible always,
2) Arrays can hold only homogeneous data elements
&
Student [] 5 = new Student [10000];
[0] = new Student; (correct)
s{t] = new Customer(); (wrong)
‘But We can resolve this problem by using object Arrays.
Object [] 0 = new Object [10000];
of0] = new Student);
oft] = new Customer();
Arrays Concept isnot implemented based on some standard data structure hence readymade method support isnot available
for every requirement we have to write the code explicitly, Which is complexity of progral‘Need Of Collections:
To overcome the above limitations of Arrays we should go for Collections,
Collections are growbable in nature. ie, Based on our requirement we can increase (or) Decrease the size,
Collections can hold both homogeneous & Heterogeneous elements.
Every Collection class is implemented based on some standard data structure, Hence readymade method support is,
availabe for every requirement. Being a programmer we have to use this method and we are not responsible to provide
implementation,Difference between Array
and Collections:
Arrays Collections
1. Arrays are fixed in size. 1, Collections are growable in nature. L.e.
based on our requirement we can
increase or decrease the size
2 Witmemory aays arent Wit to memory colletions are
recommended to use recommended to use
3 Wet Performance Arrays are 3. Wr Performance collections are nat
recommended tose recommended to use. |
Array can hold only homogeneous T Collections ean hold both homogensous
datatypeelements and heterogeneous elements
3. There is no underlying data structure for | 5, Every Collections class is implemented
arrays and hence readymade method based on some standard data structure.
support is not available Hence readymade method suppor is
available for every requirement
&_ Array can hold both primitives and Collections can hold only objects but
object types
not primitives.oe Lae
Pech koe De OES
What is Collection?Ber rok ae
What is Collection Framework?
Bae eee Cie Res Sent Min cet R itt ee tN =r
a group of objects as single entity.
DURGASOFTBt ek ae
cord To aT) Container
esa eT’ Seu me enn isp}
DURGASOFTered ee at
PET Cob er ett Sot att Oc meri ereritoter ates
i. Collection :
If we want to represent a group of individual objects as a
ETT Malis ma Rare Me Com Colm Oodle d ola
Collection interface defines the most common methods
which are applicable for any Collection object.
OMe U Ce ede i Caged
th Ta rte Me ees Bae Un
Se Beate eR eel lade)
iccac roel e tach ee \ =|
DURGASOFTEek de ee el cate
Difference between Collection & Collections
* Collection is an interface which can be used to represent
a group of individual objects as a single entity.
* Collections is an utility class present in java.util package
to define several utility methods (like Sorting, Searching..)
for Collection objects.LLG een error allecnontrnimovene at
ii. List :
* List is child interface of Collection.
* If we want to represent a group of individual objects as a
single entity where duplicates are allowed and insertion order
preserved then we should go for List.a) oo es Framework
Collection
jf z=
List (12 version
Lo
ArrayList Linked List Vector coversion
(2 version) (avesion
Stack (10version)
Note: Vector and Stack classes are re-engineer in 1.2v to implement list interfaceLiat
iii, Set:
* It is the child interface of Collection.
* If we want to represent a group of individual objects as a
single entity where duplicates are not allowed and insertion
order not preserved then we should go for Set.on Framework Pied
Collection (12verio
\
Set carson
HashSet (12 version
LinkedHashSet “«v-~aE) Ck ee Se ae
Difference between List & Set
List Set
* Duplicates are allowed * Duplicates are not allowed
* Insertion order preserved * Insertion order not preservedMeare
iv. SortedSet:
* Itis the child interface of Set.
* If we want to represent a group of individual objects as a
single entity where duplicates are not allowed but all objects
should be inserted according to some sorting orde then we
should go for SortedSet.Pek)
y. NavigableSet:
* It is the child interface of SortedSet if defines
several methods for navigation purposes.Pen Oy
Collection (1 ¢.2-erien)
Satpaons
Set ch) 12veren)
SortedSet (1 (12verion
NavigableSet «) (15+
TreeSet (12 veo26K /s % Dew Yn il Wn B
i)
vi. Queue :
* Itis child interface of Collection.
* If we want to represent a group of individual objects prior to
processing then we should go for Queue.
Exc before sending a mail all mail id's we have to store somewhere and
in which order we saved in the same order mail’s should be delivered
(First in First out) for this requirement Queue concept is the best choice.erry ial to ke
Queue: Collection w (1.2 version)
Queue wo (1.8 version)
PriorityQueue BlockingQueue (5 ,ersion
(15 version)
LinkedBlockingQueue
(15 version)
PriorityBlockingQueue
(15 version)ak Ses
Cw!
n Fra
* All the above interfaces
(Collection, List, Set, SortedSet, NavigableSet and Queue)
meant for representing a group of individual objects.
* If we want to represent a group of objects as key value pairs
then we should go for Map Interface.UDO
vii. Map:
* Map is not the child interface of Collection.
* If we want to represent a group of individual objects as
key value pairs then should go for Map.
Ex: Roll No
101
102
103
Name
Durga
Ravi
Venkat
Both key and value are objects, duplicated keys are not
allowed but values can be duplicatedeG
May o (1.2 version)
HashMap
(12 version)
WeakHashMap
((.2version)
IdentityHashMap
(1.4 version)
LinkedHashMap
(1.4 version)
Dictionary
(1.0 version)
Hashtable
| (1.0 version)
Properties
(1.0 version)10:41 AO _— Shaikan ic eR Ra
Vill ortedMap:
* Itis the child 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 SortedMap
Map 0p (12 version)
SortedMap () (12,ersion)Se ek Se ae aad
vigableMap:
* It is the child interface of sorted map, it defines several
utility methods for navigation purpose.
Map
(12 version)
SortedMap 0) ¢12 version
NavigableMap @ (1 version)
TreeMap (1.2 version,DURGASOFT|
i)
G
Ei
E
s
Sy
i
*
g
zCollection Interface :
* If we want to represent a group of individual objects as a
single entity then we should go for Collection.
* In general collection interface is considered as root interface
of Collection Framework.
* Collection interface defines the most common methods which
are applicable for any collection objectadd(Object o)
(Collection c)
remove(Object o)
removeAll(Collection c)
retainAll(Coll nc)
To remove all objects except those
present in c
clear(
contains(Object 0)
containsAll(Collection c)
olean isEmpty()
186 int size();
187 Object[] ‘toarray();
188 Iterator iterator()
189
190
191
192
193
194Important methods of Collection Interface
boolean add(Object 0)
boolean addAll(Collection c)
boolean remove(Object 0)
boolean removeAll(Collection c)
boolean retainAll(Collection c)
void clear()
boolean contains(Object 0)
boolean containsAll(Collection c)
boolean isEmpty()
int size()
object{] toArray()
Iterator iterator()for
Collection Interface
Note:
Collection interface doesn’t contain any method to retrieve objects there
is no concrete class which implements collection class directly.List Interface :
* Itis the child interface of Collection.
* If we want to represent a group of individual objects as a
single entity where duplicates are allowed and insertion order
must be preserved then we should go for List.
* We can differentiate duplicates by using index.
* We can preserve insertion order by using index, hence index
play very important role in list interface.dex, Object o)
(int index,Collection c)
Object get(int index)
Object remove(int index)
Object set(int index, Object
to replace the element present at specified index with
Provided Object and returns old object
int indexOf(Object o)
returns index of first occurrence of
istIndexOf(Object o)
‘ator [IE aPre
List interface specific methods
void add(int index, Object o)
boolean addAll(int index, Collection c)
object get(int index)
object remove(int index)
object set(int index, Object new)
int indexOf(Object o)
int lastindexOf{Object 0)
ListIterator listiterator();Pree
ArrayList
* The underlined data structure Resizable Array or Growable Array
* Duplicates are allowed.
¢ Insertion order is preserved.
* Heterogeneous objects are allowed [except TreeSet & TreeMap
everywhere heterogeneous objects are allowed].
+ Null insertion is possible.Pe
ArrayList Constructors
1. ArrayList al = new ArayList()
Creates an empty Array list object with defautt initial capacity 10.
Once Array List reaches its map capacity a new Array List will be
created with new capacity = (currentcapacity * 3/2) + 1.Paro)ArrayList Constructors
2. ArrayList al = new ArrayList(int initialCapacity);
3. ArrayList al = new ArrayList(Collection c);(ak deh eh oe
Per ok kee Creed coOise ee
Per TOR "as
ladd( >=
l.add(10);
lLadd( DS
l.add( 7
System.out.printin(1);// [A,10,A,null]
l.remove(2);
System.out.printin(1);// [A,10,null]
add(2, 7 I
l.add( =
System.out.printin(1);//[A,10,M,null,N]Example for Arraytist
i Ladd(null);
Public static vold main(String] args) [ System.out printin()); // (A, 10, A, null]
new ArrayList(); Lremove(2);
System.out.printin()); 4 (A, 10, null]
Ladd(‘2°, "m");
Ladd('n");
System.out.printin()); // [A, 10, M, null,N})
}* Usually we can use Collections to hold and transfer Objects
from one place to another place, to provide support for this
requirement every Collection already implements
Serializable and Cloneable interfaces.* ArrayList 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 then
ArrayList is the best choice.RandomAccess
* Present in java.util package.
* It doesn't contain any methods and it is a Marker interfacePere ee
eo ek Sree ee
ArrayList 12 ArrayList();
LinkedList I2 LinkedList();
System. pea Serializable);//true
System.out.prin' Cloneable);//true
System.out.; eauene RandomAccess);//true
System.out.printin( -eof RandomAccess);//falsePe
ArrayList
ArrayList 11=new ArrayList ();
LinkedList 12=new LinkedList ();
System.out.printin (11 instanceOf Serializable); //true
System.out.printin (12 instanceOf Cloneable); —_//rue
System.out.printin (1 instanceOf RandomAccess); //true
System.out.printin (12 instanceOf RandomAccess); //falseArrayList
* ArrayList is best choice if our frequent operation is retrieval operation
(Because ArrayList implements RandomAccess interfaces)
* ArrayList is the worst choice if our frequent operation is insertion or
deletion in the middle (Because several shift operation are require)Se if: Ce Natta pyi kala
ArrayList Vector
Every method present ArrayList is _| Every method present in
non synchronize LinkedList is synchronize
‘Ata time multiple threads are | Ata time only one thread is
allowed to operate on ArrayList | allowed to operate on Vector
Object and hence ArrayList is not | Object is thread safe
thread safe
Threads are not required to wait _| Threads are required to wait to
to operate on ArrayList, hence —_| operate on Vector Object and
relatively performance is high. _| hence relatively performance is
low
Introduced in 1.2 version Introduced in 1.0 version and itis
‘And itis non legacy class a legacy classHow to get synchronized version of ArrayList Object?
« By default ArrayList is Object is non-synchronized but we can get
synchronized version of ArrayList by using Collection class
synchronizedList () method.
public static List synchronizedList(List |)How to get synchronized version of ArrayList Object?
public static List synchronizedList(List !)
Non-Synchronized
ArrayList 1i=new ArrayList ();
Synchronized
List I=Collections.synchronizedList (11);How to get synchronized version of ArrayList Object?
* Similarly we can get Synchronized version of Set, Map Objects
by using the following methods of Collections class.
Public static Set synchronizedSet (Set s);
Public static Set synchronizedMap (Map m);155 PN
LinkedList
* The underlying data structure is Double Linked List.
* Insertion order is preserved .
* Duplicates are allowed.
* Heterogeneous Objects are allowed.
* Null insertion is possible.eal LinkedList
* LinkedList implements Serializable and Clonable interfaces
but not RandomAccess interface.
* LinkedList is the best choice if our frequent operation is
insertion or deletion in the middle.
* LinkedList is the worst choice if our frequent operation is
retrieval operation.Percy ae hoe 4
358
359 addFirst(Object o)
360 4d addLast(()sai 0)
361 Object getFirst()
362 Object getLast()
363 Object removeFirst()
364 Object removeLast()
365
366 ==========55=5555>=>=
367
222Bore
LinkedList
* Usually we can use LinkedList to implement stacks and queues to
provide support for this requirement LinkedList class defines following
specific methods.
void addFirst();
void addLast()
Object getFirst();
Object getLast();
Object removeFirst();
Object removeLast();LinkedList Constructors
* LinkedList I1=new LinkedList();
Creates an empty LinkedList Object
* LinkedList I1=new LinkedList(Collection c);
Creates an equivalent LinkedList Object for the given CollectionBor
LinkedList Demo program
import java.
public class LinkedListDemo {
public static void main() {
inkedList I1=new LinkedList ();
H.add (“durga”);
Il.add (30);
H.add (null
Il.add (“durga”);
ILset (0,”software
IL.add (0,”venkey
H.addFirst (“eee”);
tem.out.printin (1);//[ece,venkey,software,30,null]Itis the best choice if our frequent
operation is retrieval
ArrayList is the worst choice if our
frequent operation is insertion or
deletion
Underlying data structure for
ArrayList is resizable or growable
Array.
ArrayList implements
RandomAccess interface
Itis the best choice if our frequent
Operation is insertion and deletion
LinkedlList is the worst choice if our
frequent operation is retrieval
operation
Underlying data structure is Double
Linked List.
LinkedList doesn’t implement
RandomAccess interfaceVector
* The underlying Data structure for the vector is resizable array or growable array.
* Duplicate objects are allowed.
* Insertion order is preserved.
* ‘null’ insertion is possible.
* Heterogeneous objects are allowed.
* Vector class implemented Serializable, Cloneable and RandomAccess Interfaces.
* Most of the methods present in Vector are synchronized. Hence Vector object is
Thread-safe.
* Best choice if the frequent operation is retrieval.aa eee
add( Object 0) ----¢
add (i bx, Object 0).
addElement( Object 0):er Vector specific metho:
For adding objects :
add (Object o) [from Collection - List(|)]
add (int index, Object o) _ [from List]
addElement (Object o) [from Vector]Vector specific methods
For removing Objects :
Remove (Object o) [ from Collection ]
removeElement (Object o) [ from Vector ]
remove (int index) [ from List ]
RemoveElementAt (int index) — [ from Vector ]
clear () [ from Collection ]
removeAllElements () [ from Vector ]Vector specific methods
For Accessing Elements :
Object get (int index) [ from Collection ]
Object elementAt (int index) [ from Vector ]
Object firstElement () [ from Vector ]
Object lastElement () [ from Vector ]
Other Methods:
int size();
int capacity ();
Enumeration elements ();Constructors of vector
1) Vector v = new Vector();
- Creates an empty vector object with default initial capacity 10,
Once vector reaches it’s max capacity a new vector Object
will be Created with new capacity = 2* current capacity.
2) Vector v = new Vector(int initialCapacity);
- Creates an empty Vector Object with specified initial capacity
3) Vector v = new Vector(int initialCapacity, int incrementalCapacity);
4) Vector v = new Vector(Collection c);
- Creates an equivalent Vector Object for the given CollectionDemo program for vector
import java.util.*;
class VectorDemo {
public static void main(String arg[]) {
Vector v = new Vector ();
System.out.printin (v.capacity ());_//[10]
for (int i= O;i<10 sit+ ) {
v.addElement (i);
}
System.out.printin (v.capacity ());_//[10]
v.addElement(“A”);
System.out.printin (v.capacity ()); [20]
System.out.printin (v);Stack
*Itis a child class of Vector.
* It is specially designed class for Last In First Out order(LIFO)Constructor of Stack
Stack s=new Stack ();Ee
Methods in Stack
1) Object push(Object obj);
- For inserting an object to the stack
2) Object pop();
- To removes and returns top of the stack.
3) Object peak(),
- To Returns the top of the stack without removal of object.
4) int search(Object obj);
- If the specified object is available it returns its offset from top of the stack,
- If the object is not available then it returns -1.
5) Object pop();
- For inserting an object to the stack‘Deno program for stack
import java.util.”;
class StackDemo {
public static void main (String arg[]) {
Stack s = new Stack ();
s.push
s.push
s.push ("C");
System.out.printin(s); _//[A,B,C]
System.out.printin (s.search ("A"); //[3]
System.out.printin (s.search(": MA]Be
Three cursors of Java
* If we want to retrieve Objects one by one from the Collection,
then we should go for Cursors.
“There are three types of cursors are available in java.
* Enumeration
* Iterator
* ListlteratorBe
Enumeration
* Introduced in 4.0 version(for Legacy).
* We can use Enumeration to get Objects one by one from the
old Collection Objects(Legacy Collections).
* We can create Enumeration Object by using elements()
method of Vector class.
Public Enumeration elements ();
Example :
Enumeration e=v. elements ();Bea
Method of Enumeration
* Enumeration defines the following two methods
* public boolean hasMoreElements();
* public Object nextElement();ret
Demo program for Enumeration
import java.util.*;
class EnumaretionDemo1 {
public static void main(String arg[)) {
Vector v = new Vector ();
for (int Osit*){
v.addElement (i);
+
System.out.printin (v); /[0,1,2,3,4,5....
10)
Enumeration e = v.elements ();
}
}
while (e.hasMoreElements()) {
Integer i
if((i%02)
0)
(Integer) e.nextElement ();
System.out.printin (i); //[0 246 8 10]
}
‘System.out.printin (v);_ //[0,1,2,3,4,.
10]ror
Enumeration
Limitations of Enumeration:
* Enumeration concept is applicable only for legacy classes
and hence it is not a universal cursor.
* By using Enumeration we can get only read access and we
can’t perform remove operation.
Note: To overcome above limitations of Enumeration we should go for
Iterator.or
Tterator
1. We can apply Iterator concept for any Collection object
hence it is universal cursor.
2. By using Iterator we can perform both read and remove
operations.Tterator
* We can create Iterator object by using iterator () method of
Collection interface.
public Iterator iterator ();
Example:
Iterator itr=C. iterator();
* where C is any Collection ObjectMethods in Iterator
* Iterator interface defines the following three methods.
i. public boolean hasNext ()
ii. public Object next()
iii, public void remove()Ear
Demo program for Iterator
import java.util.";
class IteratorDemo {
public static void main(Stringf] args) { erator ter silterator (;
While (itr.hasNext ()) {
Al List F A List();
eae a Integer n= (Integer) itrnext ();
if (n%2==0)
System.out printin (n); 02468
System.out.printin (1); /[0,4,2, 40) )
System.out.printin (I); //[0,1,2,3,4...10]
}Limitations of Iterator
1. By using Enumeration and Iterator we can move only towards forward direction
and we can’t move to the backward direction, and hence these are single
direction cursors.
2. By using Iterator we can perform only read and remove operations and we can't
perform replacement of new Objects.
Note: To overcome above limitations of Iterator we should go for ListiteratorListlierator
1. By using Listlterator we can move either to the forward
direction or to the backward direction, and hence
Listiterator is bidirectional cursor.
2. By using Listlterator we can perform replacement and
addition of new Objects in addition to read and remove
operations.545 PN
ListIterator
* We can create Listlterator Object by using listiterator ()
method of List Interface.
public Listiterator listiterator ()
Example:
Listiterator itr=l. listiterator ();
* where | is any List Objectsaiaki Methods in Listlterator
* Listiterator is the child interface of Iterator and hence all methods of Iterator by
default available to Listiterator.
* Listiterator Interface defines the following 9 methods
forward direction Backward direction
1.public boolean hasNext () 4.public boolean hasPrevious()
2.public void next() 5.public void previous()
3. public int nextIndex () 6. public int previousIndex ()
other capability methods
7.public void remove()
8. public void set(Object new)
9. public void add(object new)per
Pemo program for Listiterator
import java.util.”
class ListiteratorDemo {
Public static void main (String arg) {
LinkedList I = new LinkedList ();
Ladd ("balakrishna");
Ladd ("chiru");
Ladd (“venky");
Ladd ("nag");
System.out printin (I
Ifpalakrishna, venky, chiru, nag]
Listiterator Itr = |, listiterator ();
While (Itr. hasNext ()) {
String s = (String) Itr.next ();
if (s. equals (“venky”)) {
ltr. remove (};
}else If (s. equals ("nag") {
Itradd (“chaitu");
}else if (s. equals (“chiru”)) {
ltr. set (“charan”);
}
?
‘System.out.printin (I);
iMfpalakrishna, charan, nag, chaitu]
yyListlterator
Note: Listiterator is the most powerful cursor but its limitation is, it is
applicable only for List implemented class objects and it is not a
universal cursor.Applicable for
Movement
‘Accessibility
How to get it?
Methods
Isitlegacy
Only legacy classes
Only forward
direction(single direction)
"Only read access
By using elements()
method of Veetor class
methods
hasMoreElements()
rnextElement()
“yes” (1.00)
‘ny Collection classes,
Only forward
direction(single
direction)
Both read and remove
By using iterator()
method of Collection
interface
3 methods
hasNext ()
rext()
removel)
no" (1.2V)
Serre
Only List classes
Both forward and backward direction(ti
directional)
Read ,remove, replace and addition of
new objects
By using listiterator() method of List
interface
‘Smethods
“no (L.2V)Implementation classes of cursors
import java. uti.";
class cursorDemo {
Public static void main (String [] args) {
Vector v=new Vector ()
Enumeration e=v. element ();
Iterator itr=v.iterator ();
Listlterator Itr= v.listIterator();
System.out.printin (e.getClass (). getName ()); // java.uitl Vector$1
‘System.out printin (itr. getClass (). getName ()); // java.util. Vector$ltr
System.out printin (itr getClass (). getName ()); // java.util. Vector$Listitr"Set Interface ;
Collection (12 version
\
Set
PE is2version)
HashSet SortedSet ( (12versiom
(aversion —p l SSS
NavigableSet «(1 version
LinkedHashSet |
(4 versony
‘ TreeSet (12 versionSet
1. Set is the child interface of Collection.
2. If we want to represent a group of individual objects as a
single entity, where duplicates are not allowed and insertion
order is not preserved then we should go for Set.
3. Set interface doesn’t contain any new methods. So we
have to use only Collection interface methods.HashSet
* The underlying data structure is Hashtable.
* Duplicates are not allowed. If we are trying to insert duplicates, we won't
get any compiletime or runtime errors. add() method simply retums false.
* Insertion order is not preserved and all objects will be inserted based on
hash-code of objects.
* Heterogeneous objects are allowed.
**null’ insertion is possible.
* implements Serializable and Clonable interfaces but not RandomAccess.
* HashSet is the best choice, if our frequent operation is Search operation.Constructors of HaskSet
1) HashSet h = new HashSet();
- Creates an empty HashSet object with default initial capacity 16
& default Fill Retio 0.75
2) HashSet h = new HashSetfint initalCapacity);
- Creates an empty HashSet object with specifies
& default Fill Retio 0.75
3) HashSet h = new HashSet{int initalCapacity, float loadFactor);
- Creates an empty HashSet object with specified i
& specified Load Factor (or Fill Ratio)
4) HashSet h = new HashSet{Collection c);
- For inter conversion between Collection obje¢:
initial capacity
al capacityConstructors of HashSet
Load Factor / Fill Ratio :
- After loading the how much factor, a new HashSet object
will be created, that factor is called as Load Factor or Fill Ratiaa! Demo program for HashSer
import java.util.";
class HashSetDemo {
public static void main (String [] args) {
HashSet h=new HashSet ();
h.add("B”);
h.add("C”);
h.add("D”);
h.add("2”);
h.add(null);
h.add(10);
System.out.printin (h.add(”Z”)); // false
System.out.printin (h); // [null, D, B, C, 10, Z]
3)fees
The underlying datastructure is
Hash table.
Insertion order is not preserved
Introduced in 1.2 version
iene
The underlying datastructure is
Hash table + Linked List .
(that is hybrid data structure)
Insertion order is preserved
Introduced in 1.4 version.Demo program for LinkedHasnseé
import java.util.*;
cla
iss LinkedHashSetDemo {
public static void main (String [] args) {
LinkedHashSet h=new LinkedHashSet ();
h.add(”B”);
hadd("C”);
hadd(”D”);
h.add(’2”);
hadd(null);
h.add(10);
System.out.printin (h.add("Z”));// false
System.out.printin (h); // [B, C, D, Z, null, 10]Prorat
LinkedHashSet
Note :
- LinkedHashSet is the best choice to develop cache based
applications, where duplicates are not allowed and insertion
order must be preserved.Pe
SortedSet (I)
1. It is the child interface of set.
2. If we want to represent a group of individual objects according to
some sorting order and duplicates are not allowed then we should
go for SortedSet.“SortedSet Specific methods
Object first{) -retums first element of the SortedSet
Object last() - retuns last element of the SortedSet
SortedSet headSet{Object obj) - retums the SortedSet whose elements are < obj
SortedSet tallSet(Object obj) - retums the SortedSet whose elements are >= obj
SortedSet subSet{Object obj1, Object obj2)
-retums the SortedSet whose elements are >= obj1 and 100
2. last() => 115
3. headset(104) —> [100,101,103]
4. tailSet(104) => [104,107,110,115)
5. subset(103,110) —> [103,104,107]
6. comparator’) —> null
Note :
1. Default natural sorting order for numbers Ascending order and
for String alphabetical order.
2. We can apply the above methods only on SortedSet implemented class
objects. That is on the TreeSet object._ ‘Treeset
1. The underlying data structure for TreeSet is Balanced Tree.
2. Duplicate objects are not allowed.
3. Insertion order not preserved, but all objects will be inserted according
fo some sorting order.
4. Heterogeneous objects are not allowed. If we are trying to insert
heterogeneous objects then we will get runtime exception saying
ClassCastException.
5. Null Insertion is allowed, but only once.TreeSet Constructors
1. TreeSet t=new TreeSet();
= Creates an empty TreeSet object where elements will be inserted according to
default natural sorting order.
2. TreeSet t=new TreeSet(Comparator c);
~ Creates an empty TreeSet Object where elements will be inserted according to
3. TreeSet t=new TreeSet(SortedSet s);
4. TreeSet t=new TreeSet(Collection c);Example import java.util;
class TreeSetDemo {
public static void main(String[] args) {
‘TreeSet t = new TreeSet();
tadd(‘A’);
tadd('a”);
tadd(B");
tadd(Z");
tadd(L’);
I tadd(new Integer(10)); 1 ClassCastException
tadd(null); // NullPointerException
‘System.out.printin(t); (A,B, L, Z, a]feo : E
Null Acceptance
1. For empty TreeSet as the first element null insertion is possible.
But After inserting that null if we are trying to insert any another element
we will get NullPointerException.
2. For Non empty TreeSet if we are trying to insert Null then we will get
NullPointerExcpetion.157 PN
£xample
import java.util TreeSet;
class TreeSetDemo' {
public static void main(String] args) {
TreeSet t = new TreeSet();
tadd(new StringBuffer("A’));
tadd(new StringBuffer("Z"));
tadd(new StringBuffer("L"));
tadd(new StringBuffer("B"));
System.out.printin(t); — // ClassCastException157 PN
‘Note:
1. If we are depending on default natural sorting order then objects
should be homogeneous and comparable. Otherwise we will get
tuntime exception saying ClassCastException.
2. An object is Said to be comparable if and only if the corresponding
class implements java.lang.comparable interface.
3. String Class and all wrapper classes already implements comparable
interface. But StringBuffer doesn't implement comparable interface.
** Hence in the above program we got ClassCastException **Comparable interface:
* This interface present in java.lang package it contains only one
method CompareTo().
public int Compare To(Object obj)
Example :
obj1 .CompareTo(obj2)
|-> retums -ve iff obj1 has to come before obj2
|—> retums +ve iff obj1 has to come after obj2
|-> _ retums 0 iff obji & obj2 are equal.Example
class Test {
public static void main(String] args) {
System.out.printin("A".compareTo("Z")); // -ve
Systern.out.printin("Z".compareTo("B")); // +ve
System.out.printin(’A”.compareTo("A")); /0
System.out printin("A".compareTo(null)); // NullPointerException
}
}EonCe ee Se en aoEr
* If we depending on default natural sorting order internally JVM will
call CompareTo() method will inserting objects to the TreeSet. Hence
the objects should be Comparable.
TreeSet t = new TreeSet();
tadd(’B");
tadd(‘Z"); / "Z*.compareTo("B"); +ve
tadd("A’); — // “A".compareTo("B"); -ve
System.out.printin(t); /[A, B, Z]Note:
1. If we are not satisfied with default natural sorting order or if the
default natural sorting order is not already available then we can
define our own customized sorting by using Comparator.
2. Comparable ment for Default Natural Sorting order where as
Comparator ment for customized Sorting order.‘Comparator Interface
* We can use comparator to define our own sorting (Customized sorting).
* Comparator interface present in java.util package.
* It defines two methods. compare and equals.
1) public int compare(Object obj, Object obj2)
|-—> retums -ve iff obj1 has to come before obj2
|—>_ retums +ve iff obj1 has to come after obj2
|-—> _ retums 0 iff obj1 & obj2 are equal.
2) public boolean equals();* When ever we are implementing Comparator interface, compulsory
we should provide implementation for compare() method.
* And implementing equals() method is optional, because it is already
available in every java class from Object class through inheritance.id ite A Program to insert integer objects into the Treetet si1-te he soning crc.
is descending order :
import java.utl.*;
lass TreeSetDemo3 { lass MyComparator implements Comparator {
Public static void main(String(] arya) { Public int compare(Object abj1, Object obj2) {
‘TresSett = now TresSetinew MyCompersion)}; — linet Integer I1=(Integer)obj1;
tada(t0), Integer I2=fInteger}obj2,
edd}; ilt12)
tadd(20); retum -1;
‘System.out printin(t); else
7 retum 0;
}
Output: [20,15,10,0)
DURGASOFT|Permit tl MyComparator()); ————— line1
tadd(0);, — #ve —> compere(0,10);
tadd(15); —— -ve —> compare(15,10);
tadd(20); —— +ve —> compare(20,10);
tadd(20); —— -ve —> compare(20,15);
tadd(20); —— +ve —> compare(20,10);
tadd(20); —— -ve —> compare(20,15);
tadd(20); —— 0 —> compare(20,20);
System.outprintin(t); // [20,15,10,0)* At line-1 if we are not passing comparator object then intemally JVM
will call CompareTo() method which meant for default natural sorting
order (ascending order).
In this case output is [0,10,15,20}.
* If we are passing comparator object at line1 then intemally JVM will
call compare() method which is meant for customized sorting.
(Descending order).
In this case output is [20,15,10,0]Ee eed
=a Comparator {
Public int compare(Object obj1, Object obj2) {
Integer I1=(Integer)obj1;
Integer i2=(integer)obj2,
HN return 11 CompareTo(12); 0, 10,15,20] ascending order
HM retum -11 CompareTo(I2); [20,15,10,0] descending order
J retum 12 CompareTo(I1); [20,15,10,0] descending order
MW retum -I2 CompareTo(I1); [0,10,15,20] ascending order
Mretum +4 [10,0,15,20,20] Insertion order
MH retum -1 [20,20,15,0,10] Reverse of insertion order
J tetum 0; iu
(10)
(only first element will be inserted and all the other elements are considered es duplics
}a ee 2
Leet a eter tray
Deer ae
More videos. {
Pee
adBaza Ailes prOBPa Lo MNSeHE Siving ObjecWinto the lesen dros Tone eaee
Reverse of Alphabetical order :
import java.utl*;
lass TreeSetDemo2 {
public static vold maln(Sting() args) {
‘TresSet t = new TreeSel{new MyComparator());
addRole’),
‘Ladd("ShobhaRant"}; class implements Comparator {
‘tedd(Rajakument"); Public int compare(Object obj1, Object obj2) {
tadd(’GengeBheveni"); ‘String 1 = objt.toString);
tLedd('Ramulanime"), ‘String 2 = (Sting)obj2;
‘System.out.printin(t); HT retum #2.compereTa(st);,
} retum -81.compareTo{s2);
} }
}
Output: [ ShobhaRani, Roja, Ramulamma, Rajekun pH GRE XK
RGASOFT|order is Alphabetical order:
import java.uél.*;
class TreeSetDemo10 { yi
lic static vold main(Stringf] args}
gesel eer Tasca oars
or
Laddinew dass r implements Comparator
tadd(new StingBulfer('K); Public int compare(Object obj1, Object abj2) {
Cedd(new StingBuffer(L")), String 81 = obj1.toString();
‘System.out printin(t); ‘String 82 = obj2.toString();
: fetum s1.compareTo(s2);
+
}
Output: A, K, L, Z] eaalniees
oe DUR FTNote:
* If we are defining our own sorting by Comparator, the objects
need not be Comparable.import java.util; MyComparator implements Comparator {
dass TreeSetDemo12 { bic 1,
publ sae void mai(Sting ergs} AULT IG ena
ee eae WyCompareiion); 82=0bj2. 4
tae Grae C4; roy int Ht=st Jengih(;
‘ada StingBufie AA); wa
edd OC), retum -1;
else iftt>12)
retum 1;
else
retum s1.compareTo(82);
Output: [A,AA,XX,ABC,ABCD]
DURGASOFT|Note:
1.If we are depending on default natural sorting order then objects
should be homogeneous and comparable otherwise we will get
runtime exception saying ClassCastException.
2.But if we are defining our own sorting by comparator then objects
need not be homogeneous and comparable. we can insert
heterogeneous non comparable objects also.SE Cee ke en ko
1) For predefined Comparable classes like String default natural sorting order
already available. If we are not satisfied with that, we can define our own
sorting by Comparator object.
2) For Predefined non comparable classes like StringBuffer, default natural sorting
order is not already available. We can define required sorting by implementing
Comparator interface.
3) For our own classes like Employee, Student, Customer), the person who is
writing our own class, he is responsible to define default natural sorting order
by implementing Comparable interface.
The person who is using our class, if he is not satisfied with default natural
sorting order, then he can define his own sorting by using Comparator.
DURGASOFT|oda Demo program for Customized sorting for Employe? tis. + .ce 1 -f 3;
import java.util";
dass Employee implements Comparable { public int compare To(Object obj) {
String name; int eid! = this.eld;
inteid; Employes e = (Employee}obj,
Employee(String name, int eld) { int eid2 = e.eid;
this.name = name; iffeid1 < eid2) {
thie.eld = eld; retum -1;
} Jelse if (eid > eid2) {
public String toString() { retum 1;
return name+"—"+eld; }elee{
} return 0;
}
}
}Employes e5 = baw Emplyen ng 0),
‘TreeSet t = new TreeSei();
tadd(et);
tiedd(e2),
tadd(e3);
tedd(e4),
tadd(e5);
‘System. out printn(t;
TreaSet tt = new TreeSet{new MyComparator)};
tadd(et);
tt.edé(e2)aa Demo m for Customized sorting for Employee class: ‘Pace 30!" 3)
class MyComparator implements Comparator {
public int compare(Object obj1, Object obja) {
Employee ei = (Employee)obj1;
Employee e2 = (Employee)obj2;
String s1 = e.name;
String s2 = e2.name;
return si.compareTo(s2);ery
ferries
“1 Mlsmeant for deft netuelsortrg order.
2 Present injvalang padage
{This lterface defies only one method compare).
4. Alwrapper laste and Sting dass implement comparable
Interface,
ererrie cs
41 Rlsmesnt for customized sorting order.
2. Present in jal package
4. This interface defines to methods compare snd eq
‘4 The ony implemented clases of Comparator ae Collator and
fuletaredcolator.Derry
1. Underlying Data Structure
220KB/s % D Le
Hashtable + Unte dst
oo
Babnced Tree
Not applcae
"sorte er
“Heterogeneous objets
| Saco
‘tll acceptance
eC
alowed
Not lowed
‘oes ony ence)
RoRABPIBE
‘lowed
Not Awd
"REE
Not allowed
Not Allowed
For Empty Teese as fst lament
uli alowed and nallother cases
we wilget lPomierexptionDURGASOFT
wwwidurgasoft.com5 and values are objects only i
‘keys are not allowed but values can be dublic:
value pair is called Entry. Hence Map is cons:Sct put (object key, object val)
vone Key value pair to the map
‘the key already present then old value will be replaced wit
valueure a eee)
Mea ots w EVENT TC Mole LX] ery! Teenie
Dees ci
DON cd ee
aporswipeuptoses al -mDURGASOFT
www.durgasoft.comDURGASOFT
wwwidurgasoft.comDURGASOFT
wwwiduirgasoft.comDURGASOFT
wwwidurgasoft.com