Page – 42 Page - 55
Core Java OOPs Concept: Object-Oriented Programming (OOP) is a methodology or paradigm (describes distinct concepts or thought patterns) using "objects" and class to design program/applications program/applications Object: !n object is a real orld entity (pen# chair) hich ha$ing its on state and beha$ior beha$ior %tate o& an object is the current data and beha$ior is implemented as methods Ex: - ! car has some properties li'e model# &uel type etc hich are the state (or properties) o& that object ithin ban'ing system# ustomer is an object hich participates in day to day acti$ity acti$ity
Class: ! class is a group o& objects that ha$e common property property *t is a template or blueprint &rom hich objects are created ! class in ja$a contains+ ,ata member ethods onstructor .loc'
1: Inheritance: Inheritance: *t is a mechanism in hich one object acuires the properties and beha$ior o& its parent0s objects hich are accessible only only *t represents *%-! relationship USE: 1+ or ethod O$erriding (3un ime polymorphism) 2+ or code 3eusability Keywor: etends Exa!ple: 6mployee 6mployee)
programmer (*%-! relationship means programmer is a type o&
"hy !#ltiple inheritance not s#pporte by Java$
o o reduce the compleity compleity and simpli&y simpli&y the language
%ypes o& Inheritance:
7otes+ •
hen e create Object o& subclass then its constructor 8rst calls its super class constructor
•
Pri$ate member or methods not acuired by its subclass !nd also e cannot o$erride pri$ate/8nal methods
': Encaps#lation: ( ,ata hiding and pre$ent &rom other user ) 6ncapsulation is a process o& rapping code and data together in a single unit *t is ay to achie$e data hiding *t can be achie$ed by using access modi8er pri$ate# protected and public e sa our computer P9 bo daily but e can0t sa the internal things o& that Exa!ple+ e bo because our P9 bo raps the &unctionality o& P9 !s ode PO:O class is an eample .orderactory .order actory class is a good eample o& 6ncapsulation# hich encapsulate creation logic o& .order *vanta+e:
1 ore ;eible and easy to change ith ne reuirements 2 a'es unit testing easy < !llos you to control ho can access hat 4 =elps to rite immutable class in :a$a hich is a good choice in multi- threading en$ironment 5 6ncapsulation reduce coupling o& modules and increase cohesion inside a module because all piece o& one thing are encapsulated in one place > 6ncapsulation allos you to change one part o& code ithout a?ecting other part o& code ,esi+n Pattern base on Encaps#lation in Java: 1: actory Pattern: *s used to create object better than creating object using ne operator ': Sin+leton pattern: Use:
1+ 9sed to design loose coupling and high cohesion o& code 2+ !llos you to control ho can access hat
.: *bstraction *bstraction (/iin+ i!ple!entation) !bstraction is a process o& hiding the implementation details and shoing the reuired &unctionality to the user user *t helps to reduce the compleity and also impro$es the maintainability o& the system "ay to *chieve: 1: !bstract class 2+ *nter&ace
6ample+ 3eal li&e eample is mobile e are using its &unction li'e recei$ing recei$ing a call# ma'ing calls and listening music but e don@t 'no ho they implemented ode+ Car abstract class class Car { ignition(); ignition(); public abstract void } Car class Mazda extends class Mazda extends Car { ignition(){ ignition(){ public void System.out.println("Code .println("Code for starts Mazda engine"); engine"); } } Car class Audi extends class Audi extends Car { ignition(){ ignition(){ public void System.out.println("Code .println("Code for starts Audi engine"); engine"); } } Test public class class Test { main(String[ args) main(String[ public static void { Car !ar new Mazda(); new Mazda(); !ar.ignition(); !ar new Audi (); new Audi !ar.ignition();
} }
%o you ha$e a ar object but it can hold objects &rom aAda or !udi and it can call the appropriate ignition method he ar object does not 'no anything about the implementations o& this method it just 'no that it can call it
0: Poly!orphis!: (One inter&ace act as di?erent in di?erent class )
Polymorphism is an Oops concept hich ad$ice use o& common inter&ace instead of doing code concrete implementation hile riting code he ord Bpolymorphism0 Bpolymorphism0 literally means Ba state o& ha$ing many shapes0 or Bthe capacity capacity to ta'e on di?erent &orms0 Polymorphism in :a$a has to types+ 1+ Co!pile ti!e poly!orphis!/ static polymorphism (static binding) 6ample+ O$erloading 2+ #nti!e poly!orphis! poly!orphis!/ dynamic polymorphism (dynamic binding) 6ample+ O$erriding Static poly!orphis! 2Overloain+: (Chan+e in para!eter passe) • •
• •
*n O$erloading# parameter types/order/number o& parameters must be di?erent !t compile time# :a$a 'nos hich method to in$o'e by chec'ing the method signatures %o# this is called co!pile ti!e poly!orphis! or static binin+ onstructor can be o$erloaded ith in same class only but not o$erride onstructor method doesn@t speci&y a return type# they return instance o& class itsel&
,ynamic Polymorphism/ O$erriding+ he method to call is determined determined at runtimeC this is called called yna!ic binin+ or late binin+ 1+ O$erriding method 3US% ha$e the same argument list (i& not# it might be a case o& o$erloading) 2+ O$erriding method 3US% ha$e the same return typeC the eception is covariant return (used as o& :a$a 5) <+ O$erriding method 3US% 4O% ha$e more restricti$e access modi8er# but 3*5 ha$e less 3*5 ha$e
4+ 5+ >+ D+ E+
restricti$e one !bstract methods 3US% be o$erridden inal methods C*44O% be o$erridden %tatic methods C*44O% be o$erridden onstructors C*44O% be o$erridden Pri$ate methods C*44O% be o$erridden
4otes: •
•
If the reference reference type is a class, the object it refers refers to MUST be either that same type or a subclass of that type. If the reference reference type is an INTERFA INTERFAE, the object it refers to MUST be an object from a class !hich implements the interface.
• •
An object in "a#a that passes more than one IS$A tests is polymorphic in nature E#ery object in "a#a passes a minimum of t!o IS$A tests% one for itself an& one for 'bject class
Co#plin+ vs Cohesion: Co#plin+ is the degree to hich one class 'nos about another class Foose coupling is a good programming strategy Cohesion: he term cohesion is used to indicate the degree to hich a class has a single# ell-&ocused purpose he more &ocused a class is# the higher its cohesi$eness 6ene7ts:
he 'ey bene8t o& high cohesion is that such classes are typically much easier to maintain than classes ith lo cohesion !nother bene8t o& high cohesion is that classes ith a ell&ocused purpose tend to be more reusable than other classes 3e!ory *llocation:
he :G di$ided the memory into &olloing sections 1 =eap 2 %tac' < ode 4 %tatic his di$ision o& memory is reuired &or its e?ecti$e management
he coe section contains your bytecoe he Stac8 section o& memory contains !ethos9 local variables an re&erence variables he /eap section contains Objects (may also contain re&erence $ariables)# arrays9 instance variable he Static section contains Static ata2!ethos *bstract vs Inter&ace: Si!ilarity between *bstract vs Inter&ace: 1+ .oth cannot be instantiated 2+ !ll abstract methods o& !bstract class and inter&ace must be implemented in its subclass
,i;erence between *bstract vs Inter&ace: 1+ !bstract class needs to etends but inter&ace needs to implements 2+ ultiple inheritance is possible using inter&ace but not ith abstract class <+ *t is practically not possible to add methods to an inter&ace a&ter it is released ithout changing eisting classes but you can add a concrete method to an abstract class ithout
brea'ing the eisting classes 4+ ith !bstract class e can minimiAe the accessibility o& classes and members but in inter&ace all o& the class0s methods &rom inter&ace must be declared public 5+ !bstract class can ha$e concrete methods but inter&ace contains pure abstract methods Inter&ace: !n inter&ace is not a class *t is an entity that is de8ned by the ord *nter&ace !n inter&ace has no implementationC it only has the signature or in other ords# just the de8nition o& the methods ithout the body
H! constructor cannot be abstract# static# 8nal# nati$e# or synchroniAed
Collection: *t is a collection o& Object in a single unit 6ach collection class implements loneable and %erialiAable inter&ace
ector? 3aintain @insertion orerA an it is @Index Based’
Fist inter&ace is the sub inter&ace o& collection *t contains methods to insert and delete on inde basis
1: *rray
1+ !rraylist is groable by I(Old capacity H 2) J1K 2+ an contain duplicate element <+ aintain insertion order 4+ 7ot %ynchroniAed 5+ 3andom access because array or's at inde basis >+ anipulation slo because lots o& shi&ting needs to be occurred hile delete# insert operation D+ Lou can add any no o& 79FF E+ etch elements easily as compared to lin'ed list Iteration "ays: 1: .y iterator inter&ace IOnly tra$erse in &orard directionK ': .y &or-each loop .: Fist*terator Itra$erse in both directions# used &or Fist onlyK 0: 6numeration+ 9sed to tra$erse Gector/ Properties =as methods+ boolean has3oreEle!ents( )9 Object nextEle!ent( ) 3ethos: 1+ add() 2+ add!ll(ollection c)
<+ retain!ll()- it copies only common elements and delete others 4+ remo$e!ll()- remo$e &rom 8rst to all elements presents in second/ time compleity o(nM2) because it or' on to loops 5+ clear()- arraylist become blan' and time compleity is O (n) ':
*t is a collection o& Object# it etends !bstractFist and *mplements Fist and ,eue inter&ace 1+ 9ses doubly lin'ed list to store elements *t is node basedC each node contains the address o& its pre$ious node# ,ata $alue and net node 2+ an contain duplicate elements <+ aintain *nsertion order 4+ 7ot synchroniAed 5+ 7o random access >+ anipulation (insertion and deletion) &ast# no need o& shi&ting o& elements D+ an be used as list# stac' or ueue E+ *t0s 8rst and last must be null .: >ector: =aintain insertion order ?
Gector implements a dynamic array *ts capacity is increase by I2 H old capacityK *t is similar to !rrayFist# but ith to di?erences+ •
Vector is synchronized .
•
Vector contains many legacy methods that are not part of the collections framework.
!rrayFist and =ashap superseded Gector and =ashable but it is used to support old code run
(tack
[&oncrete class –vale!
). Vector
[&oncrete class –vale!
There is only one legacy interface called Enumeration NOTE: All the legacy classes are synchroni*ed
/ashtable class: Diference between HashMap and Hashtable /ashtable /ash3ap
=ashtable class is synchroniAed
=astap is not synchroniAe
.ecause o& hread-sa&e# =ashtable is sloer than =ashap
=ashap or's &aster
7either 8ey nor val#es can be null
One 8ey and many val#es can be null
Order o& table remain constant o$er time constant o$er time
does not guarantee that order o& map remain
Properties class
1 Properties class etends /ashtable class 2 *t is used to maintain list o& $alue in hich both 'ey and $alue are Strin+ < Properties class de8ne to constructor Properties() Properties(Properties de&ault) 4 One ad$antage o& Properties o$er /ashtable is that e can speci&y a de&ault property that ill be use&ul hen no $alue is associated ith a certain 'ey ,ictionary
=ashable
Properties
SE%: =/ashSet9
=ash%et etends AbstractSet and implements Set inter&ace *t contains uniue elements ! =ash%et is a collection set that neither allos duplicate elements nor order or position its elements *t creates a collection that uses a hash table &or storage =ash table stores in&ormation by using a mechanism called hashing he hash code is then used as an inde at hich the data associated ith the 'ey is stored
!bstractollection
!bstract%et
Iterable Inter&ace: *mplementing this inter&ace allos an object to be the target o& the "&oreach" statement
ethods+ iterator()##3eturns an iterator o$er a set o& elements
*mplementing this inter&ace allos an object to be the target o& the "&oreach" statement
/*S/SE%: 7ot inde based means &or &etching elements e need to tra$erse &rom start
1+ 9nordered 2+ 7on-synchroniAed <+ !lloed null $alues 4+ 9niue elements 5+ Per&ormance is higher than Fin'ed=ash%et and ree set >+ etch elements using iterator/&oreach loop D+ 7o guarantee o& *teration order •
7o get (*nde) method in set inter&ace
onstructor+
=ash%et( ) =ash%et(ollection c) =ash%et(int capacity) =ash%et(int capacity# ;oat 8ll3atio) /ash 3ap or /ash Set e heard to parameters that is loa &actor an initial capacity
':
*t maintains doubly lin'ed list !nd returns elements in insertion order Per&ormance is li'e(add# remo$e# contains) to be same but Fin'ed hash set slightly belo that o& $as%Set# due to the added epense o& maintaining the lin'ed list# ith one eception ! lin'ed hash set has to parameters that a?ect its per&ormance+ initial capacity and load factor %ynchroniAed Fin'ed hashset+ ! &in'ed$as%Set reuires time proportional to the size o& the set# regardless o& its capacity Set s Colle!tions.syn!%ronizedSet(ne &in'ed$as%Set(...));
1+ 2+ <+ 4+ 5+
*nsertion Ordered 7on-synchroniAed !lloed null $alues 9niue elements Per&ormance is loer than =ash%et but more eNcient than ree set(sloer due to sorting operation) >+ etch elements using iterator/&oreach loop D+ uarantee o& *teration in insertion order E+ *teration more epensi$e i& siAe is large
ail-ast vs ail-Sa&e: ail-ast: ail-&ast occurs hen a structure o& ollection is modi8ed since *teration has begun %tructural modi8cation o& a collection includes adding# deleting# updating elements o& a collection ail-&ast is identi8ed internally using a modi8cation count &or the collection and i& the iterator realiAes that the count is changed# it ill thron a ConcurrentModicationException. ecept through the iterator@s on remoe method ail-Sa&e: ail-sa&e are similar to &ast-&ail but they do not thro an 6ception hen ollection is modi8ed since they or' on a clone o& the collection CopyOnWriteArrayist and Concurrent!as"Map are &ail-sa&e iterators hich or' on a copy o& a collection &or modi8cation 4O%E ail-sa&e iterators are too costly since a clone o& a collection is created
.: %reeSet:
I%tore elements in natural order because it implements 7a$igable%et inter&ace hich implements %orted%etK
pu*li! !lass TreeSet e+tends A*stra!tSet,- implements /aiga*leSet,-0 Clonea*le0 Serializa*le
ree %et uses internally comparator &or sorting his implementation pro$ides guaranteed log(n) time cost &or the basic operations (add# remo$e and contains) 1+ 2+ <+ 4+ 5+
!scending/natural Ordered 7on-synchroniAed !lloed null $alues i& only one element is there ie null otherise compilation come 9niue elements Per&ormance is sloer than =ash%et and Fin'ed=ash%et due to sorting operation hile addition) >+ etch elements using iterator/&oreach loop D+ uarantee o& *teration in natural order E+ *teration more epensi$e i& siAe is large
or synchroniin+ %ree Set #se: SortedSet s Colle!tions.syn!%ronizedSortedSet(ne TreeSet(...));
!ll elements inserted into the set must implement the Compara*le inter&ace Constr#ctor: pu*li! TreeSet(Comparator,1 super - !omparator) pu*li! TreeSet(Colle!tion,1 e+tends - !) pu*li! TreeSet(SortedSet,- s)
D#e#e: ! 2ueue is a collection &or holding elements prior to processing .esides basic Colle!tion operations# ueues pro$ide additional insertion# remo$al# and inspection operations
ueue is an inter&ace basically orders the elements in *O
6ach 2ueue method eists in to &orms+ (1) One thros an eception i& the operation &ails# and (') he other returns a special $alue i& the operation &ails (either null or false# depending on the operation) (.): 2ueue implementations generally do not allo insertion o& null elements because hen e &etch the element it ill be $ery diNcult to 8nd hether it return $alue or &etching &rom 6mpty ueue Type of Operation
Throws exception/ reason
Returns special value/ Return
+nsert
add(e)34ut of !apa!ity e add
offer(e) # false
,emove
remoe()##-mpty 2ueue
poll() # null
-amine
element()3-mpty 2ueue
pee'()
# null
Exception Occured 5llegalState-+!eption /oSu!%-lement-+!eption /oSu!%-lement-+!eption
*n a *O ueue# all ne elements are inserted at the tail o& the ueue *t is possible &or a 2ueue implementation to restrict the number o& elements that it holdsC such ueues are 'non as bounded *& e add elements beyond its capacity then add method thros 6ception *t remo$es elements &rom pee'
%he ,eB#e Inter&ace: ! ,eue is a double-ended-ueue ! double-ended-ueue is a linear collection o& elements that supports the insertion and remo$al o& elements at both end points Prede8ned classes li'e Array6e7ue and &in'ed&ist implement the 6e7ue inter&ace
e!ue "ethods Type of Operation
#irst Element $%e&innin& of the instance'
Deque
(ast Element $End of the instance'
)nsert
add8irst(e) offer8irst(e)
add&ast(e) offer&ast(e)
Remove
remoe8irst() poll8irst()
remoe&ast() poll&ast()
Examine
get8irst() pee'8irst()
get&ast() pee'&ast()
Insert: hen the capacity o& the
Deque
6e7ue instance
is restricted# the pre&erred methods are offer8irst and offer&ast because add8irst might &ail to thro an eception i& it is &ull
,eue is same as ueue but ueue or' on *O concept but ,eue or' on both *O and F*O PriorityD#e#e: An unbounded priority queue based on a priority heap. The elements of the priority queue are ordered according to their natural ordering or by a Comparator provided at queue construction time, depending on which constructor is used. The head of this queue is the least element with respect to the specified ordering. As elements are added to a priority queue, its capacity grows automatically
1: Not ynchroni!ed. ": Time comple#ity is O (log(n)) $: %mplements &ueue.
3ap: The 'ap is an interface which describes a mapping from (eys to values, without duplicate (eys. )ach pair (nown as Map.Entry
6ntry is sub inter&ace o& ap so e can access 'ey $alue pair in ap6ntry ! set o& these map entries can be obtained by calling a map@s entrySet ( ) method *terating o$er a map is done by iterating o$er this set o methods in 6ntry+1+ public Object getQey() 2+ public Object getGalue()
6ither a #ey or many $alues can be null 3aps classes: 1+ =ashap 2+ =ashable <+ reeap 4+ Fin'ed=ashap 1: /ash3ap: =9nordered# one null 'ey ? /ash3ap
Extens
!bstractap
i!ple!ents
ap
he =ashap is a class hich stored 'ey-$alue pair and it is used to per&orm some basic operations such as insertin+# eletin+ # and locatin+ elements in a Map he $as%Map class is roughly eui$alent to $as%ta*le# ecept that it is unsynchroniAed and permits nulls 1+ *t may ha$e one 7ull Qey and multiple null $alues 2+ *t maintains 7O Order <+ hen e add $alue on same 'ey then $alue gets o$erride no error occurred 4+ 9nsynchroniAed 5+ =ashing techniue used hile adding elements >+ ime compleity depends on capacity# so it0s $ery important not to set the intial capacity too high (or the load &actor too lo) i& iteration per&ormance is important
apacity R no o& buc'ets in the =ashtable
Foad &actor R =o &ull the hash table is alloed to get be&ore its capacity is automatically increased
Lou can synchroniAe the map also+ ap m R ollectionssynchroniAedap(ne =ashap())C fail$fast + i& the map is structurally modi8ed at any time a&ter the iterator is created# in any ay ecept through the iterator@s on remoe or add methods# the iterator ill thro a Con!urrentModifi!ation-+!eption
':
hashmap
i!ple!ents
ap
! Fin'ed=ashap is implemented using both =ash table and lin'ed list implementation o& the 3ap inter&ace
*t contains $alue based on 'ey *t etends hashmap and implements ap *t maintains a lin'ed list o& the entries in the map 1+ 2+ <+ 4+
6lements retrie$e in insertion- order *t is non-synchroniAed One null 'ey and many null $alues alloed *& e insert null 'ey again it o$erride# no eception occur
.: /ash %able: =7o null 'ey or Galue# unorderedK ! hashable is an array o& Fist# each list is 'non as a buc'et he position o& buc'et is identi8ed by calling hashcode() method Extens
,ictionary
i!ple!ents
ap
his class implements a hashtable# hich maps 'eys to $alues !ny non-n#ll object can be used as a 'ey or as a $alue *t uses hashode() and euals() methods to retrie$e and store object in hashtable *ts constructor can contain initial capacity and load &actor hen the number o& entries in the hashtable eceeds the product of t"e load factor and t"e current capacity # the capacity is increased by calling the re%as% method
Points: 1+ *t contains only uniue 'ey elements 2+ 7o null 'ey or $alue alloed otherise it ill thro 7ullPointer6ception at runtime <+ *t is synchroniAed
4ote: One buc'et can store more than one 'ey-$alue pair
D#es: I& two i;erent objects have sa!e /ashCoe9 how /ash3ap will retrieve these two objects$ *4S: *t store both the Object at the same hashcode $alue# ith in the same buc'et(as a lin'ed list in single buc'et)# but hile &etching it 8rst 8nd the appropriate hashcode buc'et and then comparing the 'ey using euals method to identi&y the eact 'ey and then &etch the corresponding $alue 0: %ree3ap:= 7atural/%orted Order on 'ey basis ? I!ple!ents- 7a$igableap(etends %ortedap inter&ace)# loneable# %erialiAable Extens- !bstractap Use: he reeap implementation is use&ul hen you need to tra$erse the 'eys &rom a collection in a sorted manner %orted according to the natural order &or the 'ey@s class (see Compara*le)# or by the comparator pro$ided at creation time# depending on hich constructor is used
4avi+able Set:( Java ): he 9aa.util./aiga*leSet inter&ace is a subtype o& the 9aa.util.SortedSet inter&ace *t beha$es li'e a SortedSet ith the eception you ha$e na$igation methods a$ailable in addition to the sorting mechanisms o& the SortedSet !ctually 7a$igable %et pro$ides some ne methods to ma'e it easy in operations in present collection classes oncurrent%'ipFist%et is one o& the class hich implements 7a$igable%et
*ll S#perinter&aces:
ollectionS6T# *terableS6T# %etS6T# %orted%etS6T *ll Known I!ple!entin+ Classes: Conc#rrentS8ip
3ethos: 1 escenin+Iterator() an escenin+Set() ' heaSet()9 tailSet() an s#bSet()+ return sortedset . ceilin+()9 Foor()9 hi+her() an lower() 0 pollirst() an poll
Points: 1: A Navigableet may be accessed and traversed in either ascending or descending order. ": This interface additionally defines methods poll*irst and poll+ast that return and remove the lowest and highest element, if one e#ists, else returning null. $: ubsets of any Navigableet must implement the Navigableet interface. : 7ote that sorted sets o& Compara*le elements intrinsically do not permit null.
Proble! with 4avi+ableSet: *& e &etch/remo$e elements &rom this set than it returns $alue but i& there is no $alue then it returns null# but this inter&ace do not permit null to remo$e this ambiguity *& you add then it thro runtime eception- null pointer
4avi+able3ap (Java ): /aiga*leMap in Java 6 is an extension of SortedMap like TreeMap which provides convenient
navigation method like loer:ey, floor:ey, !eiling:ey and %ig%er:ey. /aiga*leMap is added on Java 1.6 and along with these popular navigation method it also provide ways to create a Sub Map from existing Map in Java
*ll S#perinter&aces:
apSQ#GT# %ortedapSQ#GT
*ll Known S#binter&aces:
oncurrent7a$igableapSQ#GT
*ll Known I!ple!entin+ Classes:
Extens %ortedap
Conc#rrentS8ip
3ethos: 3ethos inherite &ro! inter&ace java#tilSorte3ap !omparator0 entrySet0 first:ey0 'eySet0 last:ey0 alues
3ethos inherite &ro! inter&ace java#til3ap !lear0 !ontains:ey0 !ontainsalue0 e7uals0 get0 %as%Code0 is-mpty0 put0 putAll0 remoe0 size
1+ lowerEntry: et#rns a 8ey-val#e !appin+ associate with the +reatest 8ey strictly less than the +iven 8ey9 or
null i&
there is no s#ch 8ey
%hrows: ClassCast-+!eption -
i& the speci8ed 'ey cannot be compared ith the 'eys currently
in the map /ull
i& the speci8ed 'ey is null and this map does not permit null
'eys
': lowerKey: et#rns the +reatest 8ey strictly less than the +iven 8ey9 or there is no s#ch 8ey
null i&
.: FoorEntry: et#rns a 8ey-val#e !appin+ associate with the +reatest 8ey less than or eB#al to the +iven 8ey9 or null i& there is no s#ch 8ey 0: FoorKey: et#rns the +reatest 8ey less than or eB#al to the +iven 8ey9 or i& there is no s#ch 8ey
null
G: ceilin+Entry: et#rns a 8ey-val#e !appin+ associate with the least 8ey +reater than or eB#al to the +iven 8ey9 or null i& there is no s#ch 8ey : ceilin+Key: et#rns the least 8ey +reater than or eB#al to the +iven 8ey9 or null i& there is no s#ch 8ey
H: hi+herEntry: et#rns a 8ey-val#e !appin+ associate with the least 8ey strictly +reater than the +iven 8ey9 or null i& there is no s#ch 8ey : hi+herKey: et#rns the least 8ey strictly +reater than the +iven 8ey9 or there is no s#ch 8ey : 7rstEntry: 3eturns a 'ey-$alue mapping associated ith the least 'ey in this map# or map is empty
null i&
null i&
1: lastEntry 3eturns a 'ey-$alue mapping associated ith the greatest 'ey in this map# or the map is empty
the
null i&
11: pollirstEntry 3emo$es and returns a 'ey-$alue mapping associated ith the least 'ey in this map# or null i& the map is empty 1': poll
3eturns a re$erse order /aiga*leSet $ie o& the 'eys contained in this map he set@s iterator returns the 'eys in descending order he set is bac'ed by the map# so changes to the map are re;ected in the set# and $ice-$ersa *& the map is modi8ed hile an iteration o$er the set is in progress (ecept through the iterator@s on remoe operation)# the results o& the iteration are unde8ned he set supports element remo$al# hich remo$es the corresponding mapping &rom the map# $ia the 5terator.remoe# Set.remoe# remoeAll# retainAll# and !lear operations *t does not support the add or addAll operations
1: s#b3ap /aiga*leMap,:0 subMap(: from:ey0 *oolean from5n!lusie0 : to:ey0 *oolean to5n!lusie)
3eturns a $ie o& the portion o& this map hose 'eys range &rom from:ey to to:ey *& from:ey and to:ey are eual# the returned map is empty unless from-+!lusie and to-+!lusie are both true The retrned map will throw an 5llegalArgument-+!eption on an attempt to insert a key otside of its range/ or to constrct a sbmap either of whose endpoints lie otside its range. 1H: hea3ap /aiga*leMap,:0 headMap(: to:ey0 *oolean in!lusie)
3eturns a $ie o& the portion o& this map hose 'eys are less than (or eual to# i& in!lusie is true) to:ey The retrned map will throw an 5llegalArgument-+!eption on an attempt to insert a key otside its range. 1: tail3ap /aiga*leMap,:0 tailMap(: from:ey0 *oolean in!lusie)
3eturns a $ie o& the portion o& this map hose 'eys are greater than (or eual to# i& in!lusie is true) from:ey he returned map is bac'ed by this map# so changes in the returned map are re;ected in this map# and $ice-$ersa he returned map supports all optional map operations that this map supports The retrned map will throw an 5llegalArgument-+!eption on an attempt to insert a key otside its range. 1: s#b3ap SortedMap,:0 subMap(: from:ey0 : to:ey)
3eturns a $ie o& the portion o& this map hose 'eys range &rom from:ey# inclusi$e# to to:ey# eclusi$e (*& from:ey and to:ey are eual# the returned map is empty) he returned map is bac'ed by this map# so changes in the returned map are re;ected in this map# and $ice-$ersa he returned map supports all optional map operations that this map supports -0ivalent to su*Map(from:ey0
true0 to:ey0 false).
Speci7e by: su*Map in
inter&ace
SortedMap,:0
': hea3ap SortedMap,:0 headMap(: to:ey)
3eturns a $ie o& the portion o& this map hose 'eys are strictly less than to:ey he returned map is bac'ed by this map# so changes in the returned map are re;ected in
this map# and $ice-$ersa he returned map supports all optional map operations that this map supports The retrned map will throw an 5llegalArgument-+!eption on an attempt to insert a key otside its range. -0ivalent to %eadMap(to:ey0
false).
Speci7e by: %eadMap in
inter&ace
SortedMap,:0
'1: tail3ap SortedMap,:0 tailMap(: from:ey)
3eturns a $ie o& the portion o& this map hose 'eys are greater than or eual to from:ey he returned map is bac'ed by this map# so changes in the returned map are re;ected in this map# and $ice-$ersa he returned map supports all optional map operations that this map supports he returned map ill thro an 5llegalArgument-+!eption on an attempt to insert a 'ey outside its range 6ui$alent to tailMap(from:ey0 true)
%i!e Co!plexity: his implementation pro$ides guaranteed log(n) time cost &or the remoe operations
!ontains:ey# get# put and
Map m Colle!tions.syn!%ronizedMap(ne TreeMap(...));
1+ he ordering maintained by a sorted map 2+ ree ap is not synchroniAed <+ %orting on the basis o& comparator or comparable 4+ *t cannot ha$e null 'ey but can ha$e null $alue
4ote: 1: ime ompleity+
or() U or() or()
// to &or loop inside n J n R 2n
V // one outer-T outer must be multiply 'nLn M'nN' M O ('nN') time compleity Collectionsort(array
!rrayFist contains object must implements comparable/comparator# i& not implemented then it must be implement comparable/comparator eplicitly
Co!parator vs Co!parable: 1+ 9se comparable hen e need to compare beteen same class# and omparator inter&ace hen e need to compare ith to Object or to di?erent classes Object 2+ omparator inter&ace need to implements Bcompare()0 method and on omparable inter&ace needs to implements Bcompareo()0 methods <+ .oth returns * T :Rpositi$e# iS jR negati$e# iRj – 6uals 4+ omparable sort in natural order here omparator sort in customiAed order (you can sort in your on ays) 5+ If you see then logical difference etween these two is
Comparator in Java compare
two o!ects provided to him, while
Compara*le interface compares " t%is" reference with the o!ect specified.
# If any class implement Compara*le interface in Java then collection of that o!ect either &ist or $rray can e sorted automatically y using Colle!tions.sort(list0 !omparator) or Arrays.sort() method. # If we re%uire to sort on different parameter asis then choose Comparator interface. &or example 'mployee can e sorted on name, salary or department and clients needs an $(I to do that. Comparator implementation can sort out this prolem.
I!ple!entations: class Compara*leT%ing implements Comparable{ public String feature;== i 'no pu*li! ar is *ad... public int !ompareTo(4*9e!t o){ ==%ere t%is o*9e!t of t%is !lass !ompares itself to o*9e!t o Compara*leT%ing ot%er (Compare*leT%ing) o; return feature.!ompareTo(ot%er.feature);==so %ere t%is o*9e!t ==is !ompare#d#To ot%er o*9e!t } } class T%ingComparator implements Comparator{ public int !ompare(4*9e!t t%ing>0 4*9e!t t%ing?){ Compara*leT%ing first (Compara*leT%ing) t%ing>; Compara*leT%ing se!ond (Compara*leT%ing) t%ing?; return first.feature.!ompareTo(se!ond.feature); == ==
return first.is*n#se!ond.is*n; return se!ond.is*n# first.is*n;
8or sorting in natural order 8or sorting in reerse order
==%ere used !ompareTo of !lass String *ut important t%ing to remem*er is t%at t%is !lass is not !ompared it een doesn@t %ae any ot%er mem*er e+!ept t%is met%od }
•
•
Lou implements comparator/comparable in any class and hile using ollectionsort(list# neObject) pass Object &or sorting %tringeuals(%tring.u?er) – returns &alse because %tring.u?er does not o$erride euals method o& Object class .ut it is possible i& you use %tringcontent6uals(%tring.u?er) returns true
EB#als >s /ashCoe: euals() method is used to compare Objects &or euality hile hashode is used to generate an integer code corresponding to that object hey are used hile inserting and retrie$ing Object in =ashap# hashset %tring# *nteger already o$errides euals methods hashCoe(): (irst chec' address through hashcode on comparison o& to Objects that the object present or not i& yes then call eual method)+
*t pro$ides the hashcode o& an Object he de&ault implementation o& hashode() pro$ided by Object is deri$ed by mapping the memory address to an integer $alue p#blic native int hashCoe() EB#als(): (%hen veri&y eB#als !ethos)
*n Object class the euals methods is implemented as+ public boolean euals(Object obj) U return (this RR obj)C V %o 7n the act#al hash Coe o& any Object: E!p e!p1 M new E!p('.) int ori+inal/ashCoe M Syste!ientity/ashCoe(e!p1)
hy do e need to implements hashcode() and euals() methodsW *4S: hen e need to compare to Objects based on euals () methods# .ut e need to o$erride both methods not only hashcode ()
6ample+ Case 1: Lou can o$erride hashcode () your on ays+ public class -mp { private int age ; public -mp( int age ) { super(); this.age age; } public int %as%Code()
{ return age; } public boolean e7uals( 4*9e!t o*9 ) { boolean flag alse; -mp emp ( -mp )o*9; i( emp.age age ) flag true; return flag; } }
Case': i& e ant to store Object in =ash%et and then 8nd that object in set and remo$e any particular Object *& e pass re&erence in comparison o& objects then it ill be compare easily but i& e pass Object(ne 6P()) ith same $alue &or comparison then it needs to o$erride =ashode() and 6uals() methods Exa!ple: public class -mp> { private int age ; public -mp>( int age ) { super(); this.age age; } public int %as%Code() { return age; } public boolean e7uals( 4*9e!t o*9 ) { boolean flag alse; -mp> emp ( -mp> )o*9; i( emp.age age ) flag true; return flag; } }
public class Test-mp> { main(String[ args) public static void {
-mp> emp> new -mp>(?); -mp> emp? new -mp>(?B); -mp> emp new -mp>(?); -mp> empB new -mp>(?D); -mp> emp new -mp>(?E); $as%Set,-mp> %s new $as%Set,-mp>(); %s.add(emp>); %s.add(emp?); %s.add(emp); %s.add(empB); %s.add(emp); System.out.println("$as%Set Size###"F%s.size()); System.out.println("%s.!ontains( ne -mp>(?))###"Fhs!contains"new Emp$"%&'''( System.out.println("%s.remoe( ne -mp>(?B)###"Fhs!remove" new Emp$"%)'''( System.out.println("/o $as%Set Size###"F%s.size()); } }
O/P+ Contains and re!ove method return true i& e implements hashcode and 6uals methods else return both &alse
*ase + ,
+n this case yo want to se yor obect as key not the vale in the #ash2ap. (o yo have to override both the methods hash&ode34 and e0als34.
)mmuta-le O-ject: 1: !re automatically thread-sa&e and ha$e no synchroniAation issues 2+ ,o not need a copy constructor <+ ,o not need an implementation o& !lone 4+ he best use o& the immutable objects is as the 'eys o& a map =o to ma'e class *mmutableW
1 reate a 8nal class 2 %et the $alues o& properties using constructor only < a'e the properties o& the class 8nal and pri$ate 4 ,o not pro$ide any setters &or these properties 5 *& the instance 8elds include re&erences to mutable objects# don@t allo those objects to be changed+ 1 ,on@t pro$ide methods that modi&y the mutable objects
2 ,on@t share re&erences to the mutable objects 7e$er store re&erences to eternal# mutable objects passed to the constructorC i& necessary# create copies# and store re&erences to the copies %imilarly# create copies o& your internal mutable objects hen necessary to a$oid returning the originals in your methods
*rray >s *rray
"ethod:
16 (ystem.arraycopy3 srs/ inde/ destn/ inde/ si*e4= ?G 9aa.util.Arrays.!opy4fHange(!opy8rom0 ?0 I);
Array is a container bt Arrays is a class which is sed to perform actions on array. erial ersion 0):
he serialGersion9*, ha$e to match during the serialiAation and deserialiAation process *& it &ound di?erent then it ill thro X 5nalidClass-+!eptionY 3. What’s wrong with the deault serialersion!ID"
*& no serialGersion9*, is declared# :G ill use its on algorithm to generate a de&ault %erialGersion9*, %he e&a#lt serial>ersionUI, co!p#tation is hi+hly sensitive to class etails an !ay vary &ro! i;erent J>3 i!ple!entation # and result in an unepected *n$alidlass6ceptions during the deserialiAation process 6+ he client sends a serialiAable class ith de&ault generated serialGersion9*, (eg 12
serialGersion9*, (eg 124F) during deserialiAation process# *t raises an unepected *n$alidlass6ceptions 1+ serialGersion9*, is a static 8nal 8eld 2+ it contains Fong $alue Static I!port: ( %tatic *mport is a ne &eature added in :a$a 5 speci8cation ): +n order to access static members/ it is necessary to 0alify references with the class they came from. )#- double r 'ath.cos /'ath.0% theta23 4ut you can use directly without className through static import. )#import static 5ava.lang.ystem.out3 import static 5ava.lang.'ath.0%3 import static 5ava.lang.'ath.cos3 66 through import you can change above code as: double r cos /0% theta23
The main advantage is that yo can directly rite the static method or member $ariable name/ Main advantage of using static import in Java is saving keystrokes.
1+ !mbiguous static import is not alloed ie i& you ha$e imported ja$alangathP* and you ant to import mypac'age%omeclassP*# the compiler ill thro an error 2+ Lou cannot do static import ha$ing same name# gi$es compiler 6rror – X3emo$e 9nused importY
4ote conition abo#t Collection =Orere2Unorere9 synchronie2nonsynchronie9 #plicates2UniB#e9 Per&or!ance9 internal i!ple!entation9 n#ll allowe?
ECEP%IO4: !n exception is an e$ent# hich occurs during the eecution o& a program that disrupts the normal ;o o& the program@s instructions
"hen Occ#rre: hen an error occurs ithin a method# the method creates an object and hands it o? to the runtime system he object# called an exception ob%ect # contains in&ormation about the error# including its type and the state o& the program hen the error occurred
hen eception occurs then runtime system searches the top o& the methods in call stac' (ethods calls) &or a method that contains a bloc' o& code that can handle the eception his bloc' o& code is called an exception "andler
%hree Kins o& Exception: 1: Chec8e Exception: hec'ed 6ceptions are those 6ceptions hich occur at compile time *& ompiler doesn0t see try or catch bloc' handling a hec'ed 6ception# it thros ompilation error Exa!ple: *O6ception# %F6ception# ,ata!ccess6ception# lass7otound6ception# *n$ocationarget6ception
': Unchec8e Exception: 9nchec'ed 6ceptions are those eceptions hich occurs at runtime# hese eceptions is occur due to programming bugs# such as logic errors or improper use o& an !P* Exa!ple: !rithematic6ception# 7ullPointer6ception# 7umberormat6ception# lassast6ception# !rray*ndeOutO&.ound6ception
.: Error: 6rrors are eceptional conditions that are eternal to the application# and that the application usually cannot anticipate or reco$er &rom *t cannot be handled by program
Exa!ple: OutO&emory6rror# !ssertion6rror# Girtualachine6rror
LL Errors an r#nti!e exceptions are collectively 8nown as unchec#ed exceptions 4ote+ *& the try bloc' eecutes ith no eceptions# the 8nally bloc' is eecuted immediately a&ter the try bloc' completes *t there as an eception thron# the 8nally bloc' eecutes immediately a&ter the proper catch bloc' completes
LL Pair o& 6loc8s occ#rs as: try – catch# try-catch-8nally# try-8nally
*atchin& "ore Than One Type of Exception with One Exception 1andler:
*n :a$a %6 D and later# a single !at!% bloc' can handle more than one type o& eception his &eatures remo$es ode duplication -+#
!at!% (54-+!eptionJS2&-+!eption e+) { logger.log(e+); t%ro e+; }
4ote+ *& a !at!% bloc' handles more than one eception type# then the !at!% parameter is implicitly final *n this eample# the !at!% parameter e+ is final and there&ore you cannot assign any $alues to it ithin the !at!% bloc'
1: try bloc8: his bloc' contains code that might be able to thro an eception ': Catch 6loc8 Cat!% bloc' is an eception handler and handles the type o& eception indicated by its argument .: inally bloc8:
inally bloc' alays eecutes hether eceptions occurs or not inally bloc' may return any $alue or may thro ne 6ceptions inally bloc' is used to clean up the used resources 4O%E: 1: *& the J>3 exits/ threa eecuting the
try or !at!% code
is interr#pte or 8ille # then
the finally bloc' may not eecute ': *& Syste!exit() is called then 8nally bloc' do not get eecuted 1. An eception arising in the finally block itself. ". The death of the thread. $. The se of System.e(it)* '. Trning off the power to the &%>.
In J*>* H:
%he try-with-reso#rces State!ent: he try-ith-resources statement is a try statement that declares one or more resources ! resource is an object that must be closed a&ter the program is 8nished ith it he try-ithresources statement ensures that each resource is closed at the end o& the statement !ny object that implements 9aa.lang.AutoClosea*le# hich includes all objects hich implement 9aa.io.Closea*le# can be used as a resource
Syntax: try (eso#rce1 r eso#rce' r' ) Q
22 reso#rces +et a#to!atically close a&ter #se R Ex* try "+uered,eader br new +uered,eader"new .ile,eader"path''' { return *r.read&ine(); }
7o need to closed Bbr0 in 8nally bloc'# *t ill be closed automatically hether the try statement completes normally or abruptly Lou may declare one or more resources in a
try-ith-resources
statement+
try " /ava!util!0ip!1ip.ile 0 new /ava!util!0ip!1ip.ile"0ip.ile2ame'( /ava!io!+uered3riter writer /ava!nio!ile!.iles!new+uered3riter"output.ile4ath5 charset' ' { }
4ote+ 1+ 7ote that the !lose methods o& resources are called in the opposite order o& their creation 2+ ! try-ith-resources statement can ha$e !at!% and finally bloc's just li'e an ordinary try statement *n a try-ith-resources statement# any !at!% or finally bloc' is run a&ter the resources declared ha$e been closed
uppressed Exceptions:
!n eception can be thron &rom the bloc' o& code associated ith the try-ith-resources statement is called %uppressed 6ception Lou can retrie$e these suppressed eceptions by calling the T%roa*le.getSuppressed method &rom the eception thron by the try bloc' HH7eed o *mplements AutoClosea*le and Closea*le inter&aces &or this &eatures he Closea*le inter&ace etends the AutoClosea*le inter&ace he !lose method o& the Closea*le inter&ace thros eceptions o& type 54-+!eption hile the !lose method o& the AutoClosea*le inter&ace thros eceptions o& type -+!eption
%hrows cla#se:
hen e are not sure that the methods at hat lines may thro 6ception then you can de8ne that eception at the methods le$el *t must be compile time 6ception Fi'e *O# runtime is optional pu*li! oid rite&ist() throws 67Exception5 8rray6ndex7ut7+oundsException {
The throw tatement:
!ll methods use the
t%ro statement
to thro an eception
%ynta+ thro ne 6mpty%tac'6ception()C // ust be last statement in methods or bloc' =o to create your on 6ception+ + .y etending 6ception class Chaine Exception:
hen one 6ception is cause to thro another 6ception then this process is called chained eception Try { } !at!% (54-+!eption e) { t%ro ne Sample-+!eption("4t%er 54-+!eption"0 e); }
,e7nition: ! stac# trace pro$ides in&ormation on the eecution history o& the current thread and lists the names o& the classes and methods that ere called at the point hen the eception occurred *CCESS:
catch (6ception cause) U %tac'race6lement elementsIK R ca#se+etStac8%race() &or (int i R Z# n R elementslengthC i S nC iJJ) U %ystemerrprintln(elementsIiKgetile7ame() J "+" J elementsIiKgetFine7umber() J "TT " J elementsIiKgetethod7ame() J "()")C V V
*vanta+es o& Exceptions: &' Separating Error$!andling Code from ()egular( Code' *' +ropagating Errors ,p t"e Call Stac#' ! second ad$antage o& eceptions is the ability to propagate error reporting up the call stac' o& methods -' rouping and /i0erentiating Error 1ypes' eans 6ception accept all time o& eception occur here ile7otound6ception accept only one time o& eception
ustom 6ception+ == Main !lass public class My4n-+!eption { main(String[ a){ public static void try{ My4n-+!eption.myTest(null); } catch(MyApp-+!eption mae){ System.out.println("5nside !at!% *lo!'G "Fmae.getMessage()); } } myTest(String str) throws MyApp-+!eption{ static void i(str null){ throw new MyApp-+!eption("String al is null"); } } } == Custom -+!eption !reated and its use class MyApp-+!eption extends -+!eption { private String message null; public MyApp-+!eption() { super(); } public MyApp-+!eption(String message) { super(message); this.message message; } public MyApp-+!eption(T%roa*le !ause) { super(!ause); } K4erride public String toString() { return message; } K4erride public String getMessage() { return message; }
3U<%I-%/E*,I4: ulti threading is a process o& eecuting multiple threads simultaneously
%hrea:
! light eight sub processing# a smallest unit o& processing 3#ltitas8in+: ultitas'ing is a process o& eecuting multiple tas's simultaneously *t is used to sa$e P9 time *t can be achie$ed by+ ultiprocessing and ultithreading 3#ltiprocessin+:
1+ 6ach process has its on address in memory 2+ ost o& communication beteen process is high
3#ltithreain+: 1: hread shared the same address space 2+ ost o& communication beteen thread is lo <+ !t least one process is reuired &or each thread %hrea
"ays to create a new threa:
1+ .y etending hread class 2+ .y *mplementing B3unnable0 *nter&ace ??Thread class etends @bect class and implements ,nnable interface.
2: Runna-le )nterface:
,ae!on %hrea: ,aemon threads in :a$a are li'e a ser$ice pro$iders &or other user threads or objects running in the same process as the daemon thread ,aemon threads are used &or bac'ground supporting tas's and are only needed hile normal threads are eecuting *& normal threads are not running and remaining threads are daemon threads then the interpreter eits
,ae!on threa in Java are those thread hich runs in bac'ground and mostly created by :G &or per&orming bac'ground tas' li'e arbage collection and other house 'eeping tas's >G T%read.set6aemon(true) makes a Thread daemon ut it can only e called efore
starting Thread in Java. It will throw 5llegalT%readState-+!eption if corresponding Thread is already started or running.
)* 8nally
bloc's are not called# %tac's are not unounded and :G just eits
<+ !&ter starting a thread you cannot start that thread again i& you do so then 5llegalT%readState-+!eption o!!ur.
4+ *n ultithreading each thread runs in a separate thread call stac' 3ethos: 1: Join: 1"e t"read on 2"ic" %oin met"od calls3 stops ot"ers t"read to execute until t"is t"read completes its process. 4f you given milliseconds t"en ot"er t"read do not run up to t"at time. Priorit$ o a %hread&
LL in (1)# 7ormal (5)# a (1Z) LL hread Priority must be set be&ore start method call Sleep () - o suspend the currently eecuting thread ithin the speci8ed time# but it ill not release the loc' ;ag 7ot recommended Join () - *& any eecuting thread t1 calls join () on t2 ieC t2join () immediately t1 ill enter into aiting state until t2 completes its eecution 5iel () - ethod pauses the currently eecuting thread temporarily &or gi$ing a chance to the remaining aiting threads o& the same priority to eecute *& there is no aiting thread or all the aiting threads ha$e a loer priority then the same thread ill continue its eecution Stop () T "ait ()-
,eep Copy >s Shallow Copy: Shallow Copy: *t contains the copy o& the objects but any changes done on one object get re;ection on other object %hallo copy is a bit-ise copy o& an object ! ne object is created that has an eact copy o& the $alues in the original object *& any o& the 8elds o& the object are re&erences to other objects# just the re&erence addresses are copied ie# only the memory address is copied
,eep Copy: *t contains the copy o& the objects but any changes done on one object do not get re;ection on other object
I!portant D#estions
Interview Questions: 1: Difference between Vector and Array List?
1: 7ector is synchroni!ed and costlier whereas Array +ist is not. ": Data rowt!: A Vector defau"ts to doub"in t!e capacity of its current array# w!i"e t!e ArrayList increases its array si$e by addin e"e%ent. &: A"" %et!ods of vector are sync!roni$ed but t!is is not in Array List. ': Array List is faster t!an Vector.
(: Difference between Iterator and "ist Iterator? 1: 8e can use %terator to traverse a et or a +ist or a 'ap but +ist%terator can only be used to traverse a +ist, it can9t traverse a et. ": %terator we can travel in only one direction but with +ist%terator we can travel both directions.
ifferent (ind of traversing methods li(e ;for)"oop #w!i"e "oop#do)w!i"e#for eac! "op etc<,they all are inde# based traversing but as we (now =ava is purely ob5ect oriented language there is always possible ways of doing things using ob5ects so %terator . *raverse +ays: )numeration, %terator, +ist%terator. )numeration 7s %terator: %terator has an e#tra method >? remove/2 and if any o ther thread trying to modify the collection while iterating than it will throw Concurrent'odification)#ception.
1: Enu%eration: Met!ods used
6numeration days R $ectorelements()C 1: bool e anh a s Mo r e El e me nt s () 2 : Ob j e ctne x t El e me nt ()
(: Iterator: Met!ods used 1: hasNe#t/2 ": ne#t/2 $: remove/2 - Thr o wsI l l eg al St at eEx c ep t i oni fa nat t emp ti smadet oc al l r emo ve ()t hati sno tpr ec ededb ya c al l t one x t () . 5terator itr al.iterator(); %ile(itr.%as/e+t()) { 4*9e!t element itr.ne+t(); System.out.print(element F " "); }
&: ListIterator: Met!ods used 1 void add/@b5ect ob52 " boolean hasNe#t/ 2 $ boolean has0revious/ 2 @b5ect ne#t/ 2 int ne#t%nde#/ 2 B @b5ect previous/ 2 int previous%nde#/ 2
D void remove/ 2 E void set/@b5ect ob52
&: Difference between ,as!*ab"e and ,as!Map? 1: +ashtale is synchronied, whereas +ashMap is not ": +ashtale does not allow null keys or values. +ashMap allows one null key and any numer of null
values.
': +!at is ,as!in? Fashing means using some function or algorithm to map ob5ect data to some representative integer value. This so-called hash code /or simply hash2 can then be used as a way to narrow down our search when loo(ing for the item in the map.
-: ,as!et Vs *reeet vs Lin/ed,as!et? 1: HashSet is much faster than TreeSet. 2: HashSet doesn’t guarantee that the order of elements remains constant but in case of TreeSet it is possible.
,as!et: Gnordered, Not ynchroni!ed *reeet: Natural6orted order / -omparale is used for natural order sorting and -omparator
for custom order sorting of objects 2, Not ynchroni!ed Lin/ed,as!et: %nsertion order, Not ynchroni!ed,
0: Difference between fai")fast Iterator and fai")afe Iterator? fail-fast Iterators fail as soon as they realied that structure of -ollection has een changed since iteration has egun. It found thread realies the change in modification count then it throws Con!urrentModifi!ation-+!eption.
fail-safe iterator doesnt throw any 'xception if -ollection is modified structurally while one thread is Iterating over it ecause they work on clone of -ollection instead of original collection and that’s why they are called as fail-safe iterator. Iterator of Copy4nLriteArray&ist is an example of fail-safe Iterator also iterator written by Con!urrent$as%Map keySet is also fail-safe iterator and never throw Con!urrentModifi!ation-+!eption in Java.
hy to use H!"# $: %ull support for relational operations 2: &eturn result as 'b(ect ): *olymorphic !ueries: (olymorphic %ueries results the %uery results along with all the child o!ects if any. +: ,atabase independent: : Support for dvance features: +/0 contains many advance features such as pa gination, fetch !oin with dynamic profiling, Innerouterfull !oins. It also supports (ro!ection, $ggregation 2max, avg3 and grouping, 4rdering, 5u %ueries and 5/0 function calls.
Hebernate: /lauses in the H!" are: •
&rom
•
select
•
here
•
order by
•
group by
ggregate functions are: •
a$g(), sum(), min(), ma()
•
count(H)
•
count2...3, count2distinct ...3, count2all...3
Sub0ueries 5u%ueries are nothing ut its a %uery within another %uery. +iernate supports 5u%ueries if the underlying dataase supports it.
ifference between get and load method
get method of +iernate 5ession class returns null if o!ect is not found in cache as well as on dataase while load() 1 : method throws 4*9e!t/ot8ound-+!eption if o!ect is not found on cache as well as on dataase ut never return null
2: Get: !lways "it atabase
Load: #ay "it atabase
$% Get% et method never returns a proxy, it either returns null or fully initialied 4!ect.
"oad: load() method may return proxy, which is the o!ect with I7 ut without initialiing other properties
4+ Foad ethods per&ormance is better than et methods oA get methods call ,atabase in round trip but Foad method initialiAe a proy object ith *, and returns What is the difference between and merge and update ? &se update() if yo' are s're that the session does not contain an already persistent instance with the same identifier( and merge() if yo' want to merge yo'r modifications at any time witho't consideration of the state of the session.
/ashin+ %echniB#e: or a single character# the %as%Code is the !%** $alue or the *nteger# the $alue itsel otherise some &unction combines the object@s data bits to create the %as%Code. he same element ill generate the same hash code e$ery time *& no collisions occur hile hashing# then the search &or any elements is easy and it ill ta'e O (1) time constant
! hash nction is a &unction hich hen gi$en a 'ey# generates an address in the table
he method hasode has di?erent implementation in di?erent classes *n the %tring class# hashode is computed by the &olloing &ormula schar!t(Z) H <1n-1 J schar!t(1) H <1n-2 J J schar!t(n-1)
here s is a string and n is its length !n eample "!." R @!@ H <12 J @.@ H <1 J @@ R >5 H <12 J >> H <1 J >D R >45DE
Collisions: hen e put objects into a hashtable# it is possible that di?erent objects (by the e5uals67 method) might ha$e the same hashcode his is called a collision =ere is the eample o& collision o di?erent strings ""!a" and ".." ha$e the same 'ey+
"!a" R @!@ H <1 J @a@ R 2112 ".." R @.@ H <1 J @.@ R 2112 /ash3ap:
COE- Java I!portant Concept: 1: *rray
1+ Arrayist is faster t"an in#edist i& * randomly access its elements * thin' random access means "gi$e me the nth element" D#i: hy !rrayFist is &asterW *4S: Array&ist has direct re&erences to e$ery element in the list# so it can get the n-th element in constant time &in'ed&ist has to tra$erse the list &rom the beginning to get to the n-th element
2+ in#edist is faster t"an Arrayist for insertion8deletion !rrayFist@s sloer because the internal bac'ing-up array needs to be reallocated eason: Array&ist is sloer because it needs to copy part o& the array in order to remo$e the slot that has become &ree &in'ed&ist just has to manipulate a couple o& re&erences
<+ !rrayFist is *nde .ased hereas Fin'edFist is 7ode .ased -------------------------------------------------*rray; #############################
': S Iterator: 1: *terator is used to iterate set# list# and map but list iterator is only used to iterate only list ': *terator mo$ed only in &orard direction and list*terator mo$ed in both direction .: /ashtable >s /ash3ap:
1+ =ashtable is synchroniAed# hereas =ashap is not 2+ =ashtable does not allo null 'eys or $alues =ashap allos one null 'ey and any number o& null Galues <+ =ashap is &aster than =ashable because hashtable is synchiniAed 0: Co!parator >s Co!parable: 1: lasses should implement the omparable inter&ace to control their natural ordering here as 9se omparator to sort objects in an order other than their natural ordering "6 &omparable shold be sed when yo compare instances of same class where &omparator can be sed to compare instances of different classes.
lass class+
!L% O 6 *nstance o& class+
>. Nsing new 'eyord 2 using Class!or2ame"' < using clone"'.
4
using ob/ect deseriali0ation 4*9e!t5nputStream ois ne 4*9e!t5nputStream(); $ello %ello ($ello)ois.read4*9e!t();
Static Synchroni0ed9
8our !onditions o!!urG >G To met%ods# stati! syn!%ronized and if to t%read ant to a!!ess ea!% one met%od at a time. 89 >G Met%odG Stati! Syn!%ronized ?G Met%odG Stati! Syn!%ronized 4=p At a time one met%od !an *e a!!ess *y any one t%read and ot%er t%read ait to !all se!ond met%od. &o!' applied on t%at !lass. 5n ot%er !ase *ot% t%e met%od a!!ess randomly.
,election9