0% found this document useful (0 votes)
5 views80 pages

Unit 4 Notes

The document provides an overview of Java's Collection Framework, detailing various interfaces such as List and Set, and their respective methods. It explains the characteristics and functionalities of different collection types, including ArrayList and LinkedList, along with their methods for data manipulation. Additionally, it highlights the importance of maintaining order and handling duplicate values within collections.
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)
5 views80 pages

Unit 4 Notes

The document provides an overview of Java's Collection Framework, detailing various interfaces such as List and Set, and their respective methods. It explains the characteristics and functionalities of different collection types, including ArrayList and LinkedList, along with their methods for data manipulation. Additionally, it highlights the importance of maintaining order and handling duplicate values within collections.
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/ 80

APC)

Date:

Datshyctre whyh we Can


sere the dat

y pes cof Dala Shachye

Priihve De
Noylihoa
e boe Con, char, Linen DS

P t , dube

Arriy,t, ghset,
Linked Hsh Se et

is bav of
lollea hion Bem in wich
An primhve s
defhet Gnd

rso Collecton fmesork


defhed API in jAva and ' t
foy non primihive Ds
Datc
APCO

(olchion Franeorks
ncn -brmihve tye of do,
(ebjec k)

inttt4 :fio,2e,303;

Arays Can shre ony homescad


6) we Cah n(reae
not incrcan ordercast
sije of array a rntime
inbst fete of ( collee hon hramerk
wich þro vides fede fined cls
APCO
Dat::

I# 0s the singe ertty er object cwbch


an &bre mlhie date

Frmework -

intenfeee

mlHhle dah.'

Conteix
centK d hain baye
Note'- Collechen Franewerk
()<ava il Collechcn
(2) java wil- Mab

Collecie cbicet
* Io collcction we Can
abi Cobjech (da) sto ve he data
direeHy

Na objeet
Val

JSachin (tr rollne 4hre)


JRavi
bwe store hi dak in
ky-vale pajr.
Nhat is Collechvy Fvamelerk, Rlee hon 4 (ollehnn ?

wCollecion Franewer k
gt is an API ehich Contjns Prdetned clo

Villecheh.
9+ is the root inttce Cprend in jwK, he
of ell ha collectien objce s
Jackye)
Veolleches. clas shch ceneiny atahe
nethads

Tteeubi Intefece
enhire cUehos

(ollechon nafute extends the iteabli


Th
inteuaca Thenfore, nhery, al jakfacey
ond clohe inplebent this idefacee
to
L) The hain tuncthen ality ef is jnkafce is
þrovid

U Therefore
Gbshact me thod iteabr ret
Llevah iteraby():
APCO
Datc

Collechani
inepce ojch is þrexd in java-hl
(12 Vetion)

pubeje inefate Co(lechos KE) exted iteratl KE>

hethas

hieavchyo) collechon

Neheds o Collecen
3. Hirerachy of Collection

4. Methods of Collection interface:


Method Description
add(Object) This method is used to add an object to the
collection.
addAll(Collection c) This method adds all the elements in the given
collection to this collection.
clear() This method removes all of the elements from this
collection.
contains(Object o) This method returns true if the collection contains
the specified element.
containsAll(Collection c) This method returns true if the collection contains
all of the elements in the given collection.
equals(Object o) This method compares the specified object with
this collection for equality.
hashCode() This method is used to return the hash code value
for this collection.
isEmpty() This method returns true if this collection contains
no elements.
iterator() This method returns an iterator over the elements
in this collection.
max() This method is used to return the maximum value
present in the collection.
parallelStream() This method returns a parallel Stream with this
collection as its source.
remove(Object o) This method is used to remove the given object
from the collection. If there are duplicate values,
then this method removes the first occurrence of
the object.
removeAll(Collection c) This method is used to remove all the objects
mentioned in the given collection from the
collection.
removeIf(Predicate filter) This method is used to remove all the elements of
this collection that satisfy the given predicate.
retainAll(Collection c) This method is used to retain only the elements in
this collection that are contained in the specified
collection.
size() This method is used to return the number of
elements in the collection.
spliterator() This method is used to create a Spliterator over the
elements in this collection.
stream() This method is used to return a sequential Stream
with this collection as its source.
toArray() This method is used to return an array containing
all of the elements in this collection.
PCO
P'ae

List Set
iit is Gn index bascd dak O Sets hot inden bad data
Shuchre
2

alles

List consoredtinte l s t does nt allos to shre


elime. dliat element

ist anshre any nunber ol Dhe

nll vales. vale

we Can iferde (get) th Can iteat the se


IBenbr
eist elanes by Ie
ard istTetor inkefcc
se does not hlo h insehs
ovde. Cmesy elimn orden
Cn Gdded jn whjch orden
ahe Yericvd in bame order)

Arraylist ( );
d"add ()oo)
eadd (io); # qdd ( 2ee ).

Tteuhr its :gikr(


elkhy lih: llistLteab)
Ilevaor ita : iteraer
whilu lihashext( )) ushil( lithane0)
So-p(itenest):
soNetrheni();,
200

30
AP

Terky itTfeyaor
by
iteyrmethad by istIteror () tod

y oleehon obfec
i Araylist, liotdln, lect
Stck

tasneatl), reat), emovel)


move( ), se)

istey Cuter, we Can


ebice the clims jin brard
oy in kr'ard divee hoy. 4 backad drec hirg

CAYAorL ListIkyar cuso,


Can he
elients
APCO
1Datc
Page

Ust Arvaybistl)

wia(ei. heskat)

i-bext ()

Na(ihosrevoylO)

Sop(ei. previesl))

t h - /o
20

3o

36
20
List interface
- The List Interface in Java extends the Collection Interface and is a part of the
java.util package.
- It is used to store the ordered collections of elements. In a Java List, we can
organize and manage the data sequentially.
- Key Features:
o Maintained the order of elements in which they are added.
o Allows duplicate elements.
o The implementation classes of the List interface are ArrayList,
LinkedList, Stack, and Vector.
o It can add Null values that depend on the implementation.
o The List interface offers methods to access elements by their index and
includes the listIterator() method, which returns a ListIterator.
o Using ListIterator, we can traverse the list in both forward and backward
directions.
- Syntax:
public interface List <E> extends Collection <E>
{
// methods
{
- The implementation classes of the List interface are ArrayList, LinkedList,
Stack, and Vector. Since all the subclasses implement the List, we can
instantiate a set object with any of these classes.
o For example:
▪ List<T> al = new ArrayList<> ();
▪ List<T> ll = new LinkedList<> ();

Where T is the type of the object.

Methods of List interface:


Method Description
add(int index, Object obj) Inserts obj into the invoking list at the index passed
in the index. Any pre-existing elements at or beyond
the point of insertion are shifted up. Thus, no
elements are overwritten.
addAll(int index, Collection c) Inserts all elements of c into the invoking list at the
index passed in the index. Any pre-existing
elements at or beyond the point of insertion are
shifted up. Thus, no elements are overwritten.
Returns true if the invoking list changes and returns
false otherwise.
get(int index) Returns the object stored at the specified index
within the invoking collection.
indexOf(Object obj) Returns the index of the first instance of obj in the
invoking list. If obj is not an element of the list, -1 is
returned.
lastIndexOf(Object obj) Returns the index of the last instance of obj in the
invoking list. If obj is not an element of the list, -1 is
returned.
listIterator( ) Returns an iterator to the start of the invoking list.
remove(int index) Removes the element at position index from the
invoking list and returns the deleted element. The
resulting list is compacted. That is, the indexes of
subsequent elements are decremented by one.
set(int index, Object obj) Assigns obj to the location specified by index within
the invoking list.
iterator() This method returns an iterator over the elements
in this collection.
subList(int start, int end) Returns a list that includes elements from start to
end.1 in the invoking list. Elements in the returned
list are also referenced by the invoking object.
APCO

Arvay list
wich
bresert in javn ahe þackge

Argist is Creakd on th bass of


Yeiaba

Prokevhe o< Arraylist


O Arraylist aYe index bcyed De Shucue
OArraylist Gan Abre dilfet dah tybes or tetevajenew
Array liat om stre ufelicalk valus
Arryls Can stre any hunbea of ncall valus
5 Arraylst toelos the Snsechom ordea
doeynet follo thu sorhiny ordar
Aarigliat aY<

an aces
APCO

Ne thods ol Armylist
meted

objcet eleend) -) yed to inset a seife


elment a sheejh indn in
Arraytist

O odd object slenent) sed to alerd a seihe ee


’ -ted lsen

cddA(Collecho c) kyed to abene ali th eliment om


kohes GRechon to the ed of gen hmgist.

9 emcVe (int inda) renoves he elwen at he sheci he


/ndes in

renove all te elimnt fron

Cnbyjnd in h sehed
APCO
Dat::

retyrns
Contains (object o)

y e i redn the nunbee f clmtnz in h


Arayit
getlint index )'- retrry te elemint at thk speifec
indes in Arrag st
Betlint indeky object climet ) : sed to reslac

rdubllcËecto ) is heejhed
hrst ocuYrehee of hielimet
in the Arrayist or -)
elemen is hot there jn Arralist

to elime, otewihe etrm fle

oveL fhe cl
iteratorl)!- esed to Jetm iterator
Constru lavs in Arraylitt ;
Araylist af ne

J blank thn an Araylist (collechonc

is eretd
they Aray bist

int vale

Avraylst
ht is initialied with tha

Arrayist Method Exanplei

imbert tava- he. Arrnybst


bublic clas Moin

Arroysst al nels

alodd(to;
al. add (Bangna");
al add Corarge");
sob(al );
al add(I, Grape):
So(al); ’ otprd:to, Grabe, Bqnasy Orage
APCO

Page

Sotlalge(o)
d-Bet(a, "Kii" ):
’ o t t : Cio, Grabe

al. remove(o);
soblal); ’otpd: Csmle, kii, Orange
al remcVe C'orahe");

Sop(al)

so}lal.isErtl ): a t : faln

alcleal
Linkeslist
an jmaplerend clas of list intenface ohich
s byet in ava wie pack

cles lyslist mplurents bst, Degue


|/ Constryctors

Gkd
List
too sachin tons
lool lop2
Doubiy linbed ist

liwkadlict
O Iisesen t Delehoy dferahong au elfoent or
fast
(9) l e Gan traverse' ikellict forwavd qnd backoad
direhon both

eata shace for reviouy node addras


delahon elnent in
bl marae breviouy 4 eat ode
have to
Y0 Grked ist are indes beyd dak shcte
Linkdli Can tere hehapeneig eliment

(4 Cikd list Gan sbre ulhla null vatues

Cidiel list does nod bllos he orden


Cinteslst yochonijed colkehoh

Mehedy of Gnkellist
mehods
) Sone ethee metody of Linkels cla

Oadifinst (object elemet): insess sbeci het eames

adllast (object eliet): aßend le shechd


clie*
t he end of (inkedlst

Ginked Lis}

enove hrst):r

rnevlast()
liked list
hes Lintedlst (

. sf bent, *en enttb (coleton ()

Used to biicd an Lnted t

eleent th colechon C:

Lakllist Metinds Eenyei

ihoyt J4v9-Lubl Lnkedlis}


Clyy Mon

Ginkdlist : nes Linted4i);

el- ade ("4bc ");

eloadd (lo );

lyemove firb}();
loJ
So( i); -) opt abe, o ,

292
Ara_list Cinkedlist
DArraybst acs ay List. -Desu
OTha hndeeline dak shcre of The ndealine data shycte of

Girc ula binked st:

Ge ho shed jn

ykedli'st ae
dedehin o)ereh
inkd List
Yetial
APCO
Date :.
Page.

Venhon Java Proyjdey

Vector
Stack
Hush abl - ' y hit au clos
Prafehes

TDK 2
wyinadced

Nok' So all hen, elasesare modifed


yeiengineecd
hew Gleetho hiearcha,o tise olde cllams
Nok Lgocy cletey are
Wecor
Vetor Is a lgacy cas jnodyced in JDk 1:o
Thjs cla_braseut

clas Vecor japlimah ist

YeSisabl array
Vector lmto lost ehive
tlont) toteycd toyst
fsttemaN)
Vecter joobject tsto
t
add
clo: tor ve athedyo otka Some
(lay Vector Methsdy
D4
Gllechibn pehroried
'orde rgeahon Rley
valey hell meelhbl aAhre
tykel ditleunh
daky heterejeoneod
or Atve Gan
sctre deak basel Dndax W
Vecheyi Pofectes
PCO Date:
APCO
|Date
|Page

4) eeve Elmant (object obj)


y Cured o reve gives ofjech trom Ve chor

remaveblmntAt (j tindu)

Y2move Aa Elment ( )
ectoy:

elent
Vale

elmet
vector Va new Veeor()
Date APCO
Page

Veetor methods Enanl'

las VechrDemo
Aubtic stae void hein (stiny asl])
Vecty V he

ittethot viadd (rviray");


’vadd (1, "' Sachin"):
Vectov
methed Viadd Eliment ("rav);
Spknew-hrintinv);
Goutputivina, Sachin, mvi

Goutsa: via
Syohnout-hrinto (v lashElimNO ):

Systemerd printn(viremev Elinent(Sachin'

vi,avi]
VYenv FlintAt (1 )
APCO
Date
|Page

vYemove A ELemens (

Vecty

Vefoy V hew Vectoy

hy dfau! ahaciy
thn etov Calcib)

Dnd int valu dehie


incre apaciy)
Bydeautt Cahacit inCrcAM
by h muiahe of 2.
APCO

Avagls Veitoy

JDKf2 veglon. Vers)oy

O Arayist is not Lsgaz ceos Ljay clay


Synchvoni}ed ) Vector is schrorigad olhche
Colleche):

Not Thvead Safe Thread Sota


ABJeicaton shed is bst in

Arvayst dois neguasantte Vecty bovid the juaren}ee fox


dah cansisncq

Arrsyst doe ndsArevide or veVechoy class bovide a methed

haity g vectoy
Vetr inkeist
r
Vina
ait |tolo
deuipcdPeek wwas clas stack (0
Stack roerte,
of
Vectoy extend stk Clas
Synaxi
ackage ctl gAva bresent
in isclas stack
Clas Vectov clasa chid the
clas lejacy the stack
is U
ntaducet
Claclc
Page.
|Date:
APCO
APCO
Date

both

index byed dak stucture.


Cn Ahore heteregenes elrtnts
doy pek() oheueg Jteh
But
Yt both hethod ()pcek end
that nhn tacle+ from
t
(O
beek
hat ehrn and Sck
Stck
objeef
i gven pyh to
)o(objet
ty push
aclesi: osteiefe metod ohen Some
retody clas
inteaen
4 Colechon ntefalC stConjns )gt
Stacl' of thod Me
Date
APCO
APCO
Date
Page

eanch(object oby )

Noki hn cbjeet into sheh


hosiho

not
beolea la.

Tnu

tce is not
emt

yeu totart Stnck class


hey

clay stuck Meha


buteic

Vinmy");
2

BoHen
APCO
Pae

totd: 3
Syskrn p. þrinen (s papl));
Syskr othirden(s),

Sysknpud þritn (spee ()):

Sykh putbrink,
Tviml, eit)oo
Set Interface :
- A set is an unordered collection of objects in which duplicate values cannot be
stored. This collection is used when we wish to avoid the duplication of the
objects and wish to store only the unique objects.
- This set interface is implemented by various classes like HashSet, TreeSet,
LinkedHashSet, etc. Since all the subclasses implement the set, we can
instantiate a set object with any of these classes.
For example:
Set<T> hs = new HashSet<> ();

Set<T> lhs = new LinkedHashSet<> ();

Set<T> ts = new TreeSet<> ();

Where T is the type of the object.


vatrot
Map Lihtet
Vehon I:2 JDK initoduc
ed
al" bicked
by Hashset
is
taslei Hash Stoctye
is daa undeeine Heshel
Jlconshcors
set ineemen etHash clags
Synay'
an
Hash s
age
APCO Date:
APCO
Date
|Page

Heshet au not a indes batd data stucture


sbye the elemay acevding to heir hagh
kashad" Uale

Hashst dees hot sore dubliiat elen

Hashser Gon net shre mulhibl nul valus

elee.

Hash Se does hot feo the Jnseben order


tohtet
Key

Hshset doey not fellcs the srtiy order


Cott:2
('deebae
") rcmove h.
Cdepak,
o, Leutpti
þrinttn(hs)i but Sys
lolo): hsadd(
deepak); (" ad hs-
(Jo), hs.add
oghset( h&
Hyhset
hew
agl) (strig train veicd Athe þublic
Hashse) cley
Pagei
Date:
APCO:
APCO
Date
Page :

Hash Se Gstchor

Hashset hs

Blank (colicchen c) (jtinihatabait)

(i iniallaacits
LinkedHashSet
A LinkedHashSet is very similar to a HashSet. The difference is that this uses a
doubly linked list to store the data and retains the ordering of the elements.
Example:
// Java program to demonstrate the working of a LinkedHashSet
import java.util.*;
public class LinkedHashSetDemo
{
// Main Method
public static void main(String args[])
{
// Creating LinkedHashSet and
// adding elements
LinkedHashSet<String> lhs= new LinkedHashSet<String>();
lhs.add("Geeks");
lhs.add("For");
lhs.add("Geeks");
lhs.add("Is");
lhs.add("Very helpful");
// Traversing elements
Iterator itr = lhs.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output
Geeks
For
Is
Very helpful

Sorted Set Interface


This interface is very similar to the set interface. The only difference is that this
interface has extra methods that maintain the ordering of the elements.
The sorted set interface extends the set interface and is used to handle the data
which needs to be sorted.
The class which implements this interface is TreeSet. Since this class implements
the SortedSet, we can instantiate a SortedSet object with this class.
For example:
SortedSet<T> ts = new TreeSet<> (); Where T is the type of the object.
The class that implements the sorted set interface is TreeSet.
Tree Se

Tree Set . the direet orllerht ciay ef aavijabeses


im¬ina Sortdse) Set JJnfare

Synks
clas Treeses immet aigablSe

lConstnetors
I|method

clesreent in

y Treeset undeline dat-stucture Balonced Tre

Gn index hatd da ShhictYe


insehon_ordea
lous e forhij ord
(4o
60

3o
So
APCO

pate

jnto Treeset
whon Gopare tha
Nok methad
obyet oby) and
onhare fo (
Current hjet Corret posi hon
ity

ConloreTo (obyat cby)


methed which s
Gmhratl indefate

sed to Gonpare
steihd dject
is_reaee than
tve yale il rret bjet
ecihed object

geihed cjee

no eercel in Treedck fecan


9) Can hgt store
Synchroid dab shetre.
Bores Bonogenes elent )e Sahe date

hul yale Ganot bei e k d in Treafet.

TreeSetMehod Esae

imbort java whe *;


clos Tes)
buleic stahe veid bain (sting ag (I)
Trefet t
t& add (4o))
ts ade (bo)
tsade (2o)',
tsadd (3o);

Sykma. printn(ts)

4 Yemove( 2e):
Systeo briln (ts); ouht: [io, 3,yo,so]
Queue Interface
- The queue interface maintains the first-in-first-out order.
- It can be defined as an ordered list that is used to hold the elements that are
about to be processed.
- There are various classes, like PriorityQueue, Deque, and ArrayDeque,
which implement the Queue interface.

Queue interface can be instantiated as:


1. Queue<String> q1 = new PriorityQueue();
2. Queue<String> q2 = new ArrayDeque();

Various classes implement the Queue interface; some of them are given below:
o PriorityQueue
o Deque
o ArrayDeque
o

PriorityQueue
- The PriorityQueue class implements the Queue interface.
- It holds the elements or objects which are to be processed by their
priorities.
- PriorityQueue does not allow null values to be stored in the queue.
Consider the following example.

Example of PriorityQueue

import java.util.*;
public class Main {
public static void main(String args[]) {
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Alice");
queue.add("Daniel");
queue.add("Jones");
queue.add("Smith");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()) {
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()) {
System.out.println(itr2.next());
}
}
}

Output:
head:Alice
head:Alice
iterating the queue elements:
Alice
Daniel
Jones
Smith
after removing two elements:
Jones
Smith

Deque Interface
- The Deque interface extends the Queue interface.
- In Deque, we can remove and add the elements from both sides.
- Deque stands for a double-ended queue, which enables us to perform the
operations at both ends.

Deque can be instantiated as:


Deque d = new ArrayDeque();

ArrayDeque
- ArrayDeque class implements the Deque interface.
- It facilitates us to use the Deque. Unlike queue, we can add or delete the
elements from both ends.
- ArrayDeque is faster than ArrayList and Stack and has no capacity
restrictions.

Example of ArrayDeque

import java.util.*;
public class Main{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Lucy");
deque.add("Andrew");
deque.add("Henery");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}

Output:
Lucy
Andrew
Henery
APCO
|Datc
|lage

Map jnteeface sich þren in

) gal does no inheit CoRleehion jntekce

bubljc intertce Mas

I}hethd

intodyced vergyoy

hieyarch ef Map jneface'

Mab

heshMaal Soredu

(inkedHash4

etcena
PCO

ky-vat þaa

Key Vala

|2 Sachin
Ravi

nab i
* One key -vale þajv in
but

dupeicate
Ohe nul
vele in bt w Gan shre nunbe

Map
trder
Map interface is implemented by various classes like HashMap, TreeMap,
LinkedHashMap, etc. Since all the subclasses implement the Map, we can instantiate
a Map object with any of these classes.
Map<T, T> ages = new HashMap<>();
Map< T, T> prices = new LinkedHashMap<>();
Map< T, T> capitals = new TreeMap<>();
Where T is the type of Object.

Methods in Java Map Interface:

Methods Action Performed

This method is used in Java Map Interface to clear and remove all
clear()
of the elements or mappings from a specified Map collection.

This method is used in Map Interface in Java to check whether a


particular key is being mapped into the Map or not. It takes the key
containsKey(Object)
element as a parameter and returns True if that element is mapped
in the map.

This method is used in Map Interface to check whether a particular


value is being mapped by a single or more than one key in the
containsValue(Object)
Map. It takes the value as a parameter and returns True if that value
is mapped by any of the keys in the map.

This method is used in Map Interface in Java to create a set out of


the same elements contained in the map. It basically returns a set
entrySet()
view of the map or we can create a new set and store the map
elements into them.

This method is used in Java Map Interface to check for equality


equals(Object) between two maps. It verifies whether the elements of one map
passed as a parameter is equal to the elements of this map or not.
Methods Action Performed

This method is used to retrieve or fetch the value mapped by a


get(Object) particular key mentioned in the parameter. It returns NULL when
the map contains no such mapping for the key.

This method is used in Map Interface to generate a hashCode for


hashCode()
the given map containing keys and values.

This method is used to check if a map is having any entry for key
isEmpty()
and value pairs. If no mapping exists, then this returns true.

This method is used in Map Interface to return a Set view of the


keySet() keys contained in this map. The set is backed by the map, so
changes to the map are reflected in the set, and vice-versa.

This method is used in Java Map Interface to associate the


put(Object, Object)
specified value with the specified key in this map.

This method is used in Map Interface in Java to copy all of the


putAll(Map)
mappings from the specified map to this map.

This method is used in Map Interface to remove the mapping for


remove(Object)
a key from this map if it is present in the map.

This method is used to return the number of key/value pairs


size()
available in the map.

This method is used in Java Map Interface to create a collection


values() out of the values of the map. It basically returns a Collection view
of the values in the HashMap.
APCO

Mab Methody
imbort java

bullje she vei hain (hingllap)

map-put (lel, "vi.


hay-hud (e, "Sackin")
bmapþe3, "Raivi"):

So-p(maf- contoins key (los)); otputi- true


Seblrap CenoingVee ("binag")), o p -true
Sop(ajet (le2)); ’ oti- Sachin
map. remeve (1o 2);
Sop (ia}), - ohut- Ito) =vina), le3z Ravi
tah replate (1o3, "amit";
Sob(ap); o ; - )e) =viray) lo3egiti
PCO

hublic stte vo)d meyn

ah þut(lo), "vinay"):
kau "))
Mgb but (to2, "ami}"):

sop(ap);
63 = Ravi

Mah doy not bllow Zoehenorder


APCO
Date
|Page

Hash Map?

Hashap is an imlimend lass el hab intefae:


ws intodced TDK - Ve8Aon

Syntax'
clas Hshma imen enh Mal

lcongue hors

Hesh Map preyent in java uti2 package:


Hashna endeline datashctre is hogh tabe

Hashmah feres the catue in Key-valee paisa


valu
key
Dechar
Anit
loj Rahud Each Key-valu bar is
knewn as
shoul!
Veles Can be dyplicak
APCO
Date
P'age

orde
Hash hon Abehvon ed datn shekre

Haha Methds Exam)l'

hublie stee veid mejn (String augs (3)


Hash Ma Bm harhMap();

kns Jutl lo2, , "aaa");


|elduabak, jo2 Ghi}, lo3 aau
APCO
Date :

Rm renove (ie3);

le) debak , e 4 u i t .

Sygerout pvinen
APCO
Date:

How Gon retree Hashaþ eleu

Wertor1hfa Direetky
Twithoe asy Sel and
Tketr Iatefae )

inkfac

have a HoshMa

3lol z debak, lo2 quit

Theretor it : set ikreby ():


thie (ih hayNeat))

(Mab: Eah) ite hest ()

los YGhul
hav to w
we
Lortih

4r (Ma: aty me

jo) ’debak

lo3 yahl
lo 4 ’ kanal

husha Gnshckor

hew
Huyhma

Beank (Naj m)
ou Gan chaye
APCO
Date
age

TreeMab

|etedy

intrdued in IDk 1:2 veio

Red Black tree

Kotenh of Red Back Tru '


red or black Co lor
block

leal nad atjy the ame humber of lack hodey


shrehye'
Synchvorijed
dah
Nen S
values. hull ore nat Gn
7
Keya wrt erda forhy fk
orde
bt Ingehn floo hat doey Teeteb
cak. cay balee but should
be
y whch jnair fue da the store we
reema' Probeetes
o/
APCO
APCO
Date:
Page:

ruMa metds Exaa

bubbcSttie vojd han

hew TreMabl)

yandVel
Your bot
delak
Sptuweutinta (ngbsceltigky(i3); redtanty
APCO
Date
|Page

lo):rav)

Yeur Sorfd Ma
in whicn ouey irst

en
APCO
Date:
Paue :
fronha}

habreve( lo2):

Joutt: le62 deebek

Syykout.

bt le6 iA net
APCO

Hash tabl

clay Hshtalle inplrmenty Map

WlConshuctors

9 g also iteit Dictionay clas


jngrodyced in JD)< )-0
Ventioh

Heyhtabl linderline cat stuctyre is hashtase.

OHosh taste Conkins dthe dah in key-value air 4 ench


Key- value þir is koawn ay Enhy
'toshtasle, key shoutd alas bi
be urigut bt
ko value
Can be dublicak
Hehtatke an ah hetraueoa) elerenty or diffeat
f elennds at key Posihon
6) Haktable deey not falloss th inßeuhen rd Bohg
OYden
APCO

ychreized d t shucture

Hayhtable
Haihtabl Bt = haw
bydeful} iiHal Gpacjty

ke
Top

*Eveny key hare ih


Beshad Valee wjch

igned by Jum

are
Supbeße o2 Y4U)

no
hashcode. 3
2
Bo

Rtht (rof, "Sadin");

ht pul7, "rabQ");
APCO
Date
P'age

Hew elemens retievd from Hahtabe ?


to boHom and rijht te kaE

o
9 leg: Sachin, )?
Jo2: Yav
Difference between Hashmap and Hashtable :

S. No. Hashmap Hashtable

1. Non synchronized data structure Synchronized data structure

Multiple threads can operate At a time only one thread is allowed to


2. simultaneously and hence hashmap's operate the Hashtable's object. Hence it
object is not thread-safe. is thread-safe.

Threads are not required to wait and It increases the waiting time of the
3.
hence relatively performance is high. thread and hence performance is low.

Null is not allowed for both key and


Null is allowed for both key and
4. value. Otherwise, we will get a null
value.
pointer exception.

5. It is introduced in the 1.2 version. It is introduced in the 1.0 version.

6. It is not a legacy class It is a legacy class.


-APCO -
Date :.
Page

Propos ies class in Java

Hashtasle

Properties

ceay that is inhctied fom Hasftala


Class

4 java objech
to 4ccers Datyboge from java rogvan
nced to Creek hrean
then
have to twrik Goda in java fl t

eu held to
heed to make ar fi 4d than

ch cade, GniG an
ho Yyhrt th sevea yey )

.class Seyer

abpnes)
APCO
Date:
Pge:

Key= valy

kay val

bvehehes ie

Becay yeu to jt
and hostham to
hake froahey
key-vadt bair fhat

Yead

forcheahesP
heotnl'g2illoo 25

DB- Prhsie
Demo java

chËcct o) Prohehes clas in


APCO
Dte

Key vclit

an
ny key

o} Proehey clay

bolye void lood (1rptsegm ins

Lwith

brohy cbieet irte


APCO
Date

CouYA< þvopeahey

Pregva
impoyt java il*!
imbort

Aepeches: h Prhehsl );

HleinbShea ing 2 hew FikInbtseam( 'Ghuse þofecho )

So.();

ouput 23
n
-APC0
Date :.
Page :

bgtore (euts, "epdetd"):

t 1239 in Coyyyshroheths

Nok
Prpertis cls
len
frgeunky bvogron
G jeyn
8tart
Sorting:
Sorting collections is a fundamental operation in Java programming. The Java API provides
two powerful interfaces to handle custom sorting: Comparable and Comparator.

Comparable Interface
- Comparable interface is used to order the objects of the user-defined class.
- This interface is found in java.lang package.
- It provides a single sorting sequence only, i.e., you can sort the elements on the basis of
single data member only. For example, it may be rollno, name, age or anything else.
- Comparable interface contains a single method: compareTo().

compareTo(Object obj) method:


public int compareTo(Object obj): It is used to compare the current object
with the specified object. It returns
▪ positive integer, if the current object is greater than the specified object.
▪ negative integer, if the current object is less than the specified object.
▪ zero, if the current object is equal to the specified object.

When a class implements Comparable, its objects can be sorted automatically using methods
like Collections.sort().

✓ Collections class provides methods for sorting the elements of List type elements.

✓ Method of Collections class for sorting List elements


public void sort(List list): is used to sort the elements of List. List elements must
be of the Comparable type.

Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student implements Comparable<Student> {


private int id;
private String name;
private double gpa;

// Constructor
public Student(int id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}

// Getters
public int getId() { return id; }
public String getName() { return name; }
public double getGpa() { return gpa; }

// Implementing the compareTo method


@Override
public int compareTo(Student otherStudent) {
// Sort based on GPA (ascending order)
if (this.gpa > otherStudent.gpa) return 1;
if (this.gpa < otherStudent.gpa) return -1;
return 0;
}

@Override
public String toString()
{
return "Student [id=" + id + ", name=" + name + ", gpa=" + gpa + "]";
}
}
public class ComparableExample {
public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<>();
al.add(new Student(101, "Alice", 3.8));
al.add(new Student(102, "Bob", 3.5));
al.add(new Student(103, "Charlie", 4.0));

// Before sorting
System.out.println("Before sorting:");
for (Student s : al) {
System.out.println(s);
}

// Sorting using Collections.sort()


Collections.sort(al);

// After sorting
System.out.println("\nAfter sorting (by GPA, ascending):");
for (Student s : al) {
System.out.println(s);
}
}
}
Output:
In this example, implementing the Comparable interface allows Students to be sorted by GPA
in ascending order.
Note: If you don’t use toString() method in the above code, then output will be:

Comparator Interface in Java


- Comparator interface is used to order the objects of a user-defined class.
- This interface is found in java.util package and contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).

public int compare(Object obj1, Object It compares the first object with the second
obj2) object.

public boolean equals(Object obj) It is used to compare the current object


with the specified object.

- It provides multiple sorting sequences, i.e., you can sort the elements on the basis of
any data member, for example, rollno, name, age or anything else.

✓ Method of Collections class for sorting List elements


public void sort(List list, Comparator c): is used to sort the elements of List by the given
Comparator.

Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;

// Student class (without implementing Comparable)


class Student {
private int id;
private String name;
private double gpa;

// Constructor
public Student(int id, String name, double gpa) {
this.id = id;
this.name = name;
this.gpa = gpa;
}

// Getters
public int getId() { return id; }
public String getName() { return name; }
public double getGpa() { return gpa; }

@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", gpa=" + gpa + "]";
}
}

// Comparator for sorting by name


class NameComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getName().compareTo(s2.getName());
}
}

// Comparator for sorting by ID


class IdComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
return s1.getId() - s2.getId();
}
}

// Comparator for sorting by GPA (descending)


class GpaComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
if (s1.getGpa() > s2.getGpa()) return 1; Here interchange 1 and -1 to print in
descending order according to Gpa.
if (s1.getGpa() < s2.getGpa()) return -1;
return 0;
}
}

public class ComparatorExample {


public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<>();
al.add(new Student(101, "Alice", 3.8));
al.add(new Student(102, "Bob", 3.5));
al.add(new Student(103, "Charlie", 4.0));

// Sorting by name
Collections.sort(al, new NameComparator());
System.out.println("Sorted by name:");
for (Student student : al) {
System.out.println(student);
}

// Sorting by ID
Collections.sort(al, new IdComparator());
System.out.println("\nSorted by ID:");
for (Student student : al) {
System.out.println(student);
}

// Sorting by GPA (Ascending)


Collections.sort(al, new GpaComparator());
System.out.println("\nSorted by GPA (ascending):");
for (Student student : al) {
System.out.println(student);
}
}
}
Output:
Difference Between Comparable and Comparator :

You might also like