0% found this document useful (0 votes)
7 views19 pages

Collection

Uploaded by

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

Collection

Uploaded by

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

-if wewantto represent a group of individual objectas a single entity then we

should go for Collection


-Collection interface defines the most common methods which are aplicable for any
collection object
-methods in Collection interface boolean add(),booleanaddAll(),boolean
remove(),boolean retainAll(Collection c)-expect particular object passed in
parameter romove all o
ther object from collection,booleancontains(Object
obj),booleancontainsAll(Collection c),iboolean sEmpty(),int size(),
-Object[] toArray()-to convert collection to array,it retunr type is Object[],
-Iterator iterator() methods returns Iterator object it is used to ge tobject from
collection one by one.
Note : These all objects are present in Collection interface
Note: I have mentioned the return types of object also

...................................................................................
............................

Note : there is no concrete class which implements Collection interface directly.


...................................................................................
...
Note :In TreeSet and Treemap Herogenious object are not allowed because all object
should be inserted according to sorting order technique so comparasion is required
so theobject sould be of same type
List Interface :
It is a child interface of Collection interface
-It allows duplicates
-insertion order must be preserved
-first inserted element is inserted at index 0
-Methods in List Interface
1)void add(3,A) - Note : when we add element at 3rd index and if elemnet is present
at 3rd index it will move to 4th index
2)boolean addAll(int index,Collection c)
3)Object remove(int index)
4)Object get(int index)
5)Object set(int inex,Object o)
6)int indexOf(Object ob) :it gives index of first occuring object
7)int lastIndexOf(Object ob): it gives index of last occuring object
8)ListIterator listIterator : Has return type ListIterator

There are 4 classes that implements List Interface

1)ArrayList :

-Data structer for Arraylist is Resizable array or growable array


-Duplicates are allowed
-Insertion order preserved
-It can hold hetrogenious object
-null insertion is possible
-ArrayList l=new ArrayList(); : this creates empty Arraylist Object with the
default limit of 10 object and when we try to insert 11th object it creates a new
ArrayList with the limit of 16(formula is used to decide new limit internally)
Object is created and copy all the object and reassign the reference varaible to
new created ArrayList
-formula to decide new limit : (new capacity=current capacity*3/2)+1
-ArrayList l=new ArrayList(int initialcapacity); : By this we can create empty
ArrayList with the specified initial capacity
-ArrayList l=new ArrayList(Collection c) : creates an equivalent ArrayList Object
for the given Collection.
-Note : after syso(l) :- allthe output will be given in [] brackets but for Map it
gives o\p in {} brackets
Note : generics came after 1.5 so if after 1.5 we dont use generics it gives
excptions like unchecked or unsafe exception
Note : Usually we can use Collections to hold and transfer objects from one
location to another location to provide support for this requirement every
Collection Class implements Serializable Interface and very Collection Class
implements Clonable Interface
-We can access any random object/element with same speed so retrival is fast
because ArrayList and Vector classes implementsRandomAccess Interface
-ArrayList is the best choice if our frequentoperation is retrival
operation(because it implements Random Acess interface)
-Arraylist is worst choice if our frequent operation is insertion or deletion in
middle because when we add or remove any element from middle the next or prior
element index shifts
-in ArrayList Elemnts are stored in Conseviction memory location so retrival if
elements is faster
-LinkList is the best choice for inserion and deletion in middle

...................................................
RandomAccess Interface is marker interface so contains no methods hence required
ability is provided by JVM present in java.util package
...................................................................................
..................

Defference between ArrayList and vector :

ArrayList:
-Every methods is non-synchronized
-multiple threads are allowed to operate because every method is non-synchronized
so its not Thread-safe
-relatably performance is high
-introduced in 1.2 its non-legacy

Vector:
-Every methods is synchronized
-single thread is allowed to operate only because most of the method is
synchronized hence its Thread-safe
-relatably performance is low
-introduced in 1.0 its legacy

How to get synchronized version of ArrayList Object?


->By default ArrayList is non-synchronized but we can get synchronized version of
ArrayList object by using public static List synchronizedList() method of
Collections Class
->similarly we can get synchronized version of Set and Map objects by using the
methods of Collections Class i.e public static Set synchronizedSet() , public
static Map synchronizedMap() method

...................................................................................
.......................

LinkList is the best choice for inserion and deletion in middle. Why?
->
...................................................................................
LinkList:

-implements List Interface


-Underlined data structer isdoubled linkedlist
-insertion order is preserved
-Duplicates are allowed
-Hetrogenious object is allowed
-Null insertion is possible
-LinkList implemets Serializable and clonable interface but not random access
inteface
-LinkList is the best choice for inserion and deletion operation in middle
-LinkList is the worst choice if our frequent operation is retrival operations
-LinkList l = new LinkList() : creates an empty linklist object
-LinkList l = new LinkList(Collection c) : creates an equivalent LinkList object
for the given collection
-in ArrayList Elemnts are stored in Conseviction memory location so retrival if
elements is faster
--in LinkList Elemnts are not stored in Conseviction memory location so retrival if
elements is slower
-Usually we can use LinkList todevelop Stack and Queue to provide support for this
requirement LinkList class defines th following methods
1)void addFirst(Object o)
2)void addlast(Object o)
3)void getFirst(Object o)
4)void getlast(Object o)
5)void removeFirst(Object o)
6)void removelast(Object o)
7)void set(Object c)
8)void add(Object c)
Note : this methods are only applicable for LinkList Object

LinkdList i=new LinkedList();


i.add("durga");
i.add(30);
i.add(null);
i.add("durga");// [duga,30,null,durga]
i.set(0,"Software");//[Sofware,30,null,durga]
i.add(0,"venky");//[venky,Sofware,30,null,durga]
i.removeLast();//[venky,Sofware,30,null]
i.addfirst("CCC");//[CCC,venky,software,30,null]
syso(l);//[CCC,venky,software,30,null]

...................................................................................
..........................

Vector Class :

-Duplicated are allowed


-preserves insertion order
-Underline DATA structer for vectoris resizable arrray and growable array
-hetrogenious objects are allowed
-null insertion is possible
-vector implements serialazable,clonableandRabdomAccess interface
-vector is thead-safe
-Elemnts are stored in Conseviction memory location
-Vector has 4 constructor
-Vector V =new vector(); :-creates empty Vector Object with the default initial
capacity of 10 onceavector reaches its max capacity then thenew Vector object will
be created with the new capacity=currencapacity*2
-Vector v=new Vector(int intialcapacity) e.g Vector v=new Vector(100)
-Vector v=new Vector(int intialcapacity,int incrementalcapacity) :if we specofy
vector capacity to 1000 and imagine it gets maxed out so instead of
-Vector V =new vector(Collection c) : creates an equivalent vector object for given
collection this constructer is for interconversion betwen collection object
-vector has following methods-
1)addElement(Object o)
2)removeElement(Object o)
3)removeElement(int index)
4)removeElements(Collection c)
5)Object elementAt(int index)
6)Object firstElement()
7)Object lasElement()
8)Enumeration elements();

...................................................................................
......

Stack Class :

-child class of vector


-it adapts all propeties of vector class
-it is a specially designed Class for LIFO
-it has only one constructor
-Stack s = new Stack();
-Stack methods
1)puch(Object o)
2)pop()
3)peek() : return top of the Stack elementswithout removal
4)empty()
5)int search(Object 0):to check wheather this elemnts is there or not if there it
returns offset if not it will return -1
Note: offset?

-Stack s = new Stack();


s.push("A")
s.push("B")
s.push("C")
syso(s); //[A,B,C]
syso(s.search("A")); //-1

...................................................................................
....................

Cursors in java : to get obj one by one from collection

1)Enumeration: we can use Emumeration to get elements one by one from legacy
collection object
-we can create Enumeration object by using elements() method of vector class
-enumeration we cannot perform remove element from collection
-enumeration methods
1)public boolean hasmoreElements()
2)public Object nextElement()
-Enumeration e=v.elements();
while(e.hasmoreElements())
{
Integer I = (Integer)e.nextElement();
if(I%2==0)
{
sop(I);
}
}

2)Iterator(interface) : we can apply iterator concept for any collection object


hence it is universal cursor
-by using iterator we can perform bith the read and remove operation
-we can create Iterator object by using iterator() method of collection interface
-methods in Iterator
1)public boolean hasNext()
2)public Object next()
3)public void remove()
ArrayList l=new ArrayList();
Iterator i=l.iterator();
while(i.hasNext())
{

Integer I = (Integer)e.next();
if(I%2==0)
{
sop(I);
}
else
itr.remove();
}

Limitations of Iteratoe
-we can only move/iterate in forward direction cannot move in backward direction
-we can perform only read and remove operation we cannot perform add and replace
operation

3)ListIterator :
-It has bi-direction cursor that means we can move either in forward direction and
backward direction
-we can perform replacement and the addition on new objects in addition to read and
remove operations
-public ListIterator listIterator
-ListIterator is child Interface of Iterator
-thier are 9 methods in ListIterator :
1)public boolean hasNext()
2)public Object next();
3)public int nextIndex()
4)public boolean hasprevious()
5)public Object previous()
6)public int previousIndex()
7)public void remmove()
8)public void add(Object o)
9)public void set(Object 0) :-to replace current object with new object

-linkedList i = new LinkedList();


i.add("B")
i.add("V")
i.add("C")
i.add("N")
sop(i); //[B,V,C,N]
ListIterator itr = i.listIterator();
while(itr.hasNext())
{
String s = (String)itr.next();

Limitation of ListIterator
-the most powrful cursor is ListIterator but its limitation is it is applicable
only for List Objects

Internal implementions of cursors


Vector v = new Vector();
Enumeration e = v.elements(;
Iterator itr=v.iterator();
Listiterator litr=v.listIterator();
Sop(e.getClass().getname());//java.util.Vector$1
Sop(itr.getClass().getname());//java.util.Vector$Itr
Sop(litr.getClass().getname());//java.util.Vector$ListItr

..................................................................................

HashSet Class:
-The underline Data Structer is Hash table
-Duplicates are not allowed
-insertion order is not preserved but all
-Null insertion is possible but only one time
-Hetrogeneous objects are allowed
-hashSet implements Serializable,clonable interface
-Random accessor interface is not there
-Everywhere search operation is frequently required go for Hashing related data
structer
-hashSet is best choice if our frequent operation is search operation
-Note : in HashSet duplicates are not allowed if we are trying to insert duplicates
then we wont get any compile or run time errors and the add() method simply returns
false
HashSet h = =new HashSet();
-Constructors in HashSet
1)HashSet h = =new HashSet(); : creates empty HashSet Object with initial capacity
of 16 and default Fill Ratio: 0.75(75%)
Note : default Fill Ratio is 75% means when HashSet fills to 75% automatic new
HashSet Object will be created
Note
2)HashSet h = =new HashSet(int initialcapacity); : creates an empty HashSet Object
with initial specifieid capacity with default flll ratio 0.75
3)HashSet h = =new HashSet(int initialcapacity,float fillratio);
4)HashSet h = =new HashSet(Collection c); : interconversion of collection obj

HashSet h = =new HashSet()


h.add("B");
h.add("Z");
h.add("A");
h.add("C");
h.add("D");
SOP(h.add("A"));//false
SOP(h);// can't predict the o\p
................................................................................

LinkedHashSet Class:-Child Class of HashSet


-LinkedHashSet is exactly same like HashSet has same methods but LinkedHashSet
preservs insertion order
-Underlined Data Structer is Linked list + Hash table
-LinkedHashSet lh = =new LinkedHashSet()
h.add("B");
h.add("Z");
h.add("A");
h.add("C");
h.add("D");
SOP(h.add("A"));//false
SOP(h);// can predict the o\p because insertion order is presrved
-In general LinkedHashset to develop cache based applications where duplicates are
not allowed and insertion order is preserved

..............................................................................

SortedSet Interface: -IT is a child Interface of Set Interface


-SortedSet If we want to represent a group of individual objects according to some
sorting order without duplicates then we should go for SortedSet
-Methods in SortedSet Interface (notapplicable for Set Interfacw)
1) Object first() : returns first element of the SortedSet //100
2)Object last() : returns last element of the SortedSet //120
3)SortedSet headSet(Object obj)106 : returns SortedSet whose elements are less than
obj [100,101,104]
4)SortedSet tailSet(Object obj)106 : returns SortedSet whose elements are >= obj
[106,110,115,120]
5)SortedSet subSet(Object obj1,Object obj2) 101,115 : returns SortSet whose
elements are >=obj and < obj2 [101,104,106,110]
6)Comparator comparator() : returns Comparator object that describes underlying
sorting technique. If we are using ntural order then we will get null.

100
101
104
106
110
115
120

...................................................................................
......

TreeSet Class: implements SortedSet Interface


- TreeSet underlying Data Structer is Balanced Tree
-No duplicates
-insertion is not preserved
-Hetrogeneous Object are not allowed when we try to add we will get runtime
exeption saying classcastexception
-null insertion is possible only once
-implemets serializable clonable interface but not RandomAcess interface
-All objects will we inserted based on some sorting order it may be default natural
sorting order or custimizer sorting order
-constructors in TreeSet
1)TreeSet t = new TreeSet(); : creates empty TreeSet with default natural sorting
order
2)TreeSet t = new TreeSet(Comparator c) : creates empty TreeSet objectwhere the
object will be inserted according to customizer sorting order specified by
Comparator object
3)TreeSet t = new TreeSet(Collection c); :
4)TreeSet t = new TreeSet(SortedSet s); : for any sorted set obj eqivalent TreeSet
object will be created

Note : TreeSet t = new TreeSet() : default sorting order


Note : TreeSet t = new TreeSet(Comparator c): customizer sorting order

-TreeSet t = new TreeSet();


t.add("A")
t.add("a")
t.add("B")
t.add("Z")
t.add("L")
t.ad(new integer(10)); //CCE( exception)
t.add(null);// NPE
sop(t); //[A,B,L,Z,a]

-Null acceptance (1.6 java version)


For not empty TreeSet if we tring to insert NUll its gonna get runtime exceptions
i.e Null Pointer Exception
For empty TreeSet if we tring to insert NULL it will accept no exception is thrown

Note : until 1.6 version Null is allowed as a first element to the empty TreeSet
but from 1.7 version onwards Null is not allowed even as a first element

-TreeSet t = new TreeSet();


Note : when we call TreeSet default constructor it internally calls comparTo()
method
t.add(new StringBuffer("A"))
t.add(new StringBuffer("B"))
t.add(new StringBuffer("C"))
t.add(new StringBuffer("D"))
syso(t);
Note : if we are depending on default natural soting orer compulsory the objects
should be homogenous and comparable otherwise will give runtime exception saying
ClassCastException
Note :An object is said to becomparable if andonly if corresponding class
implements Coparable Inerfac
Note : String Class and all wrapper Classes already implements Comparable Interface
but StringBuffer Class doesnt implements Comparable Interface Hence we got
classcastexpection in above example

...................................................................................
.................

Comparable Interface : -Present in java.lang package


-It has only one method
1)public int compareTo(Objectobj) : returns int value

ob1.compareTo(obj2) : ob1:-the objectwe are trying to insert obj2:-the object


already present
returns -ve : if obj1 has to come before obj2
returns -+ve : if obj1 has to come after obj2
returns - 0 : if obj1 obj2 are equal

sop("A".compareTo("Z"));-ve
sop("Z".compareTo("K"));+ve
sop("A".compareTo("A")); 0
sop("A".compareTo(null));RE : NPE

Note :if we are depending on default natural sorting order then while adding obj
into TreeSet JVM willcall compareTo() method
TreeSet t = new TreeSet();
t.add("K")
t.add("Z")->"Z".compareTo("K") +ve Note : in treeset algo. greater means right side
t.add("A")->"A".compareTo("K") -ve
t.add("A")->"A".compareTo("K") -ve "A".compareTo("A") 0 : here second operations
because root "K" left side already have "A" element
sop(k); [A,K,Z]

Note :StringBuilder doesnt implements Comparable interface


Note:Comparable meant for default natural sorting order
Note : If default natural sorting order not availabe or be we are not satisfied
with the default natural sorting order then wecan go for customizer sorting by
using Comparator

...................................................................................
.............................................

Comparator Interface :

-present in java.util package


-methods in Comparator
1)public int compare()
returns -ve : if obj1 has to come before obj2
returns -+ve : if obj1 has to come after obj2
returns - 0 : if obj1 obj2 are equal
2)public boolean equals()

-whenever we are implementing Comparator interface complusory we should provide


implementaton nly for compare() method and we are require to provideimplementation
for equals() method because it is already available from Object Class through
inheritance

Q.Write a program to insert Integer Objects into the TreeSet where the sorting
order is descending order
->

10
/ \
15 0
/ /
20 5

TreeSet t = new TrerSet(new myComparator()); //line 1


t.add(10);

t.add(0);
//compare(0,10)

t.add(15);
//compare(15,10)

t.add(5);
//compare(5,10)
//compare(5,0)

t.add(20);
//compare(20,10)
//compare(20,15)

t.add(20);
//compare(20,10)
//compare(20,15)
//compare(20,20)

sop(t)
//{20,15,10,5,0}

class MyComparator implements Comparable


{
public int compare()
{
Integer 11 = mew(integer)obj1;
Integer 12 = mew(integer)obj2;
if(i1<i2)
return +1;
else if(i1> i2)
return -1
else
return 0;

}
}

Note : at line 1 if we arenot passing comparator object then internally JVM will
call compareTo() method which is meantfor default natural sorting order

-various possible implementations of compare() method


public int compare(Object ob1,Object ob2)
{
Integer 11 = mew(integer)obj1;
Integer 12 = mew(integer)obj2;

return I1.compareTo(I2) Dfault natural sorting order(ascending) [0,5,10,15,20]


return -I1.compareTo(I2) Descending order [20,15,10,5,0]
[]return I2.compareTo(I1) Descending order [20,15,10,5,0]
return -I2.compareTo(I1) (ascending) [0,5,10,15,20]
return +1 [Insertion order] [10,0,15,5,20,20]
return -1 reverse of insertion[20,20,5,15,0,10]
return 0 only first element will be inserted &all remainingare considered
duplicated

...................................................................................
...................

...................................................................................
............................

Map Interface :-map is not child Interface of Collection Interface


-if we want to represnt a group of obj as key-value pair then we should so for Map
interface
-Duplicate key are not allowed but values can bedupicated
-Each key-value pair is called Entry hence Msp is considered as group of Entry
Objects
-Map Interface methods
1)public Object put(Object key,Object value) : To add one key value pair to Map

m.put(101,"durga")
m.put(102,"steve")
m.put(101,"ravi") // durga will be replacedwith ravi having same 101 key associated
Note :if the key is already present then old value will be replace with new value
and returns old value

2)void putAll(Map m)

3)Object get(key) :

4)Object remove(key)

5)boolean containsKey(key)

6)boolean containsValue(vslue)

7)boolean isEmpty()

8)int size()

9)void clear();

-Collection views of map

1)Set KeySet()

2)Collection values()

3)Set entrySet()

Entry Interface: -Entry Interface is inner Interface of Map Interface

-Without existing of Map Object there is no chance of existing Entry Object hence
Entry Interface is defined inside Map Intrface
-methods of Entry interface called as entry specific methods and we can apply only
on entry object
Object setKey()
Object getValue()
Object setvalue()

.........................................................
HashMap Class :
-underlyong Data Structer is Hash Table
-insertion order not preserved it is based on hash code of keys
-duplicates key are not allowed , duplicate values are allowed
-implements serializable and clonable but not Random Access interface
-for both key value hetrogenious object is allowed
-null only once in kay,unlimited null in value
-good for serchiing technique
-Constructor
1)HashMap m = new HashMap : creates an empty HashMap object with a default initial
capacity 16 and default fill ratio 0.75
2)HashMap m = new HashMap(int initialcapacity) : creates an empty HashMap object
with the specfied initial capacity and the default fill ratio 0.75
3)HashMap m = new HashMap(int initialcapacity floatfillratio) :
4)HashMap m = new HashMap(Map m) : interconversion

-watch video durga collection part-11-1:04:01 -for program


........................................................................
Q.Different with HashMap & HashTable
-
HashMap
-not synchronized
-can operate multiple thread
-not thread safe
-performance is high
-null key allowed
-null value allowed
-it is not lagecy indrocuced 1.2

HashTable :
-synchronized
-can operate only single thread at time
-null key not allowe
-null value not allowed
-it is legcy introduced 1.0 v

...................................................................................
...............
Q.How to get sunchrozed version of HashMap Object?
->we can get synchronized version of HashMap by using Synchronizedmap() method of
Collections class
map m=Collections.synchronizedmap(m); //m is non-synchronized HashMap object
reerence
...................................................................................
..............................

LinkedHashMap : -LinkedHashMap is child class of HashMap


-underlying data structeris linkedlist +hash table
-insertion order is preserved
-introduced in 1.4v
-LinkedHasSet and LinkedHasMap are commonly used for developing cache based
applications
...................................................................................
.............
Differencebetween == operator ans .equals() methods
->in general == perator meant for reference comparasion/address comparaion whereas
.equals method meeant for content comparasion

Integer i1 - new Integer(10);


Integer i2 - new Integer(10);
sop(i1==i2)//false
sop(i1.equals(i2))//true
...................................................................................
...................

SortedMap : -child interface of Map interface


-if you want to represent group of object as group of keyvalue pair acording to
some sorting order of keys then we should go for SortedMap
-sorting is based on key but not based on vlaue
-SortedMap defines the following specpfic methods
1)Object firstKey
2)Object lastkey()
3)SortedMap headMap(Object key)
4)SortedMap tailMap(Object key)
5)SortedMap subMap(Object key, Object key2)
6)Comparator comparator()

TreeMap Class : implementation class of SortedMap Interface


-underlying Data Structer is RED-BLACK TREE
-insertion order is not preserved it is based on some sorting order of keys
-all elements is inserted according to sorting order of keys
-duplicate key is not allowed. value is allowed
- if we are depnding default NSO then the keys should be Homogenious and comparable
otherwise we will ge RE saying ClassCastException
-if we are defining our own sorting by comparator then keys need not be homogenius
and comparable wecan take hetrogenious non comparable objects also
-whether we are depending on default natural sorting order or customier sorting
order there are no restrictions for values we can take hetrogenious non comparable
objects also
-null acceptance
1)for non-empty TreeMap : if we trying to insert an Entry with a NULL key then we
will get RE saying NULLPOINTEREXPECTION

2)for empty TreeMap : as the first entry with the Null key is allowed but after
inserting that entry if we tryiing to insert any other entry then we will get RE
expection saying NULLPOINTEREXPE
Note : the above null acceptance rull applicable until 1.6 version only from 1.7
version onwards null is not allowed for key.
-four constructer
1)TreeMap t = new TreeMap(); : creates empty TreeSet with default natural sorting
order
2)TreeMap t = new TreeSet(Comparator c) : creates empty TreeSet objectwhere the
object will be inserted according to customizer sorting order specified by
Comparator object
3)TreeMap t = new TreeSet(SortedMap m); :
4)TreeMap t = new TreeSet(Map m); : for any sorted set obj eqivalent TreeSet object
will be created
-for program code example refer durga java part 13 - time : 41:28

...................................................................................
.......................

HashTable Class : - underlying Data Structer for HashTable Class is Hash table
-insertion order is not preserved it is based on hash code of keys
-duplicate keys are not allowed and values can be duplicated
-Hetrogenious Objects are allowed for both keys and values
-Null is not allowed for both key and value otherwise we will get RE saying NPE
-It implements Clonable,Serializable and clonable interfaces but not RandomAccess
Interface
-Every method present in HashTable is sychronized and hence HashTable Object is
Thread-Safe
-Hashtable is a best choice if our frequent operation is search operation
-Constructors
1)HashTable m = new HashTable : creates an empty HashMap object with a default
initial capacity 11 and default fill ratio 0.75
2)HashTable m = new HashTable(int initialcapacity) : creates an empty HashMap
object with the specfied initial capacity and the default fill ratio 0.75
3)HashTable m = new HashTable(int initialcapacity float fillratio) :
4)HashTable m = new HashTable(Map m) : interconversion

...................................................................................
.....

Properties :-in our program if somethings chances frequently like username,email ID


etc. or not recommended to hard code in java program because if there is any change
to reflect that chnage recompilation,rebuild and redeploy application are required
even sometimes server restart is also required which creates a big impact to the
client.
-we can overcome this problem by using properties file such type of varaible things
we have to configure in properties file
-from that properties file we have to read into java program and we can use those
properties
-the main advantage of this approach is if there is a chnage in properties file to
reflect that chnage just redeployment is enough which wont create any impact to
theclient
-we can use java Properties Object to hold properties which are coming from
properties file
-in normal Map (like HashMap,HashTable,TreeMap) key and value can be anytype but
incase of Properties ket and value should be String type
-constructor
1)Properties p = new Properties();
-methods
1)String getProperty(Sring pname); : to set new Property
Note : if specified property is already available old value will replaced with new
value and returns new value
2)String(return old value) setProperty(String pname,String pvalue); : to get value
associated with the specified property
Note : if specified property is not availbale then this method returns null

3)Enumeration 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 properties from java


properties object into properties file

-for program example : durga java part 14- time 1:22:03 .

..................................................................................
1.5v enchanchments(Queue Interface)
Queue interface :-Child interface of collection interface
-if we want to represent a group of individual objects prior to processing then we
should go for Queue
-for example : before sending sms message we have to store all mobile numbers in
some Data Structer in which ordered we added mobile numbers in same order only
message should be sent for this FIFO requirement Queue is the best choice
-Usually Queue follows FIFO order but based on our requirement we can implement our
own Priority order also(Priority Queue)
-from 1.5v onwards LinkList Class also implements Queue Interface
-LinkList based implementation of Queue always follows FIFO
-Queue Interface specific methods
1)booleanoffer(Object o) : to add object into the queue
2)pull() : to remove and return head element of the queue. If queue is empty then
this method returns null
3)remove() : to remove and return head element of the queue. If queue is empty then
this method raises RE : NoSuchElementException
4)Object peek() :to return head element of the queue. If queue is empty then this
method returns null
5)Object element() : to return head element of the queue. If queue is empty then
this method raises RE : NoSuchElementException

Priority Queue Class : -if we want to represent a group of indvidual objects prior
to processing according to some priority then we should go for prioroty queue
-the priority can be defauld natural sorting order or customizer sorting order
defined by compararator
-insertion order is nor prserved it is based on some priority
-duplicated not allowed
-if we are depending on default natural sorting order compulspry object should be
homogenious and comparable otherwise we will get RE: CCE
-if we are defining our own sorting by comparator then objects need not be
Homoenious and comparable
-null is not allowed even as the first element also
-constructors
1)PriorityQueue q=new PriorityQueue() :Creates an empty PriorityQueue with default
initial capacity 11 and all object will be inserted according to default sorting
natural order
2)PriorityQueue q=new PriorityQueue(int initialcapacity) :
3)PriorityQueue q=new PriorityQueue(int initialcapacity,Comparator c);
4)PriorityQueue q=new PriorityQueue(Sorted s)
5)PriorityQueue q=new PriorityQueue(Collection c):

class PriorityQueueDemo
{
psvm()
{
PriorityQueue q=new PriorityQueue(15,new MyComparator());
q.offer("A")
q.offer("Z")
q.offer("L")
q.offer("B")
SOP(q);//[Z,L,B,A]
}
}
class MyComparator implements Comparator
{
public int compare(Object obj1,Object obj2)
{
String s1=(String)obj1;
String s2=obj2.toString();
return s2.compareTo(s1);
}
}

...................................................................................
...............................
Enhancment of 1.6v

NavigableSet Interface:- it is a child inteface of SortedSet and it defines several


methods for navigation purposes
-floor(e) : returns highest element which is less then or equal to e
-lower(e) : returns highest element which is less thene
-ceiling(e) : returns lowest element greater or equal to e
-higher(r) : returns lowest element which is greater then e
-pollFirst : remove and return first element
-pollLast() : remove annd return last element
-descendingSet(): it returns NavigableSet in reverse order

Note : Can we used onlly for TreeSet Object as implementing class is TreeSet

class NavigableSet
{
PSVM()
{
TreeSet t = new TreeSet();
t.add(1000);
t.add(2000);
t.add(3000);
t.add(4000);
t.add(5000);
SOP(t);//[1000.2000.3000.4000.5000]
SOP(t.ceiling(2000))//2000
SOP(t.higher(2000))//3000
SOP(t.floor(3000))//2000
SOP(t.lower(3000))//2000
SOP(t.pollFirst())//1000
SOP(t.pollLast())//5000
SOP(t.descendingSet)//[4000,3000,2000,1000]
SOP(t)//[2000,3000,4000]
]
}

NavigableMap Interface :-child interface of SortedMap Interface


-it defines several methods for navigation purposes
-Navigable Map defines the following methods
1)-floorKey(e) : returns highest element which is less then or equal to e
-lowerKey(e) : returns highest element which is less thene
-ceilingKey(e) : returns lowest element greater or equal to e
-higherKey(r) : returns lowest element which is greater then e
-pollFirstEntry : remove and return first element
-pollLastEntry() : remove annd return last element
-descendingMap(): it returns NavigableSet in reverse order

...................................................................................
..................

Collections Class :- Collections Class defines several utility methods for


collection objects like sorting,searching,reersing etc.
-can be used to sort List Object
-Collections Class defines the following 2 Sort methods
1)public static void sortOf(List l); : will be sorted according to D N S O but List
should compulsory contain homogenious and comparable objects otherwise we will get
RE : CCE
Note : List should not contain NULL otherwise we will get NPE

2)public static void sortOf(List l,Comparator c) : to sort based on customizer


sorting order

You might also like