Unit 4 Notes
Unit 4 Notes
Date:
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
(olchion Franeorks
ncn -brmihve tye of do,
(ebjec k)
inttt4 :fio,2e,303;
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
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
U Therefore
Gbshact me thod iteabr ret
Llevah iteraby():
APCO
Datc
Collechani
inepce ojch is þrexd in java-hl
(12 Vetion)
hethas
hieavchyo) collechon
Neheds o Collecen
3. Hirerachy of Collection
List Set
iit is Gn index bascd dak O Sets hot inden bad data
Shuchre
2
alles
Arraylist ( );
d"add ()oo)
eadd (io); # qdd ( 2ee ).
30
AP
Terky itTfeyaor
by
iteyrmethad by istIteror () tod
y oleehon obfec
i Araylist, liotdln, lect
Stck
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<> ();
Arvay list
wich
bresert in javn ahe þackge
an aces
APCO
Ne thods ol Armylist
meted
Cnbyjnd in h sehed
APCO
Dat::
retyrns
Contains (object o)
rdubllcËecto ) is heejhed
hrst ocuYrehee of hielimet
in the Arrayist or -)
elemen is hot there jn Arralist
oveL fhe cl
iteratorl)!- esed to Jetm iterator
Constru lavs in Arraylitt ;
Araylist af ne
is eretd
they Aray bist
int vale
Avraylst
ht is initialied with tha
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
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
Mehedy of Gnkellist
mehods
) Sone ethee metody of Linkels cla
Ginked Lis}
enove hrst):r
rnevlast()
liked list
hes Lintedlst (
eleent th colechon C:
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
Ge ho shed jn
ykedli'st ae
dedehin o)ereh
inkd List
Yetial
APCO
Date :.
Page.
Vector
Stack
Hush abl - ' y hit au clos
Prafehes
TDK 2
wyinadced
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
remaveblmntAt (j tindu)
Y2move Aa Elment ( )
ectoy:
elent
Vale
elmet
vector Va new Veeor()
Date APCO
Page
las VechrDemo
Aubtic stae void hein (stiny asl])
Vecty V he
Goutsa: via
Syohnout-hrinto (v lashElimNO ):
vi,avi]
VYenv FlintAt (1 )
APCO
Date
|Page
vYemove A ELemens (
Vecty
hy dfau! ahaciy
thn etov Calcib)
Avagls Veitoy
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
eanch(object oby )
not
beolea la.
Tnu
tce is not
emt
Vinmy");
2
BoHen
APCO
Pae
totd: 3
Syskrn p. þrinen (s papl));
Syskr othirden(s),
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<> ();
elee.
Hash Se Gstchor
Hashset hs
(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
Synks
clas Treeses immet aigablSe
lConstnetors
I|method
clesreent in
3o
So
APCO
pate
jnto Treeset
whon Gopare tha
Nok methad
obyet oby) and
onhare fo (
Current hjet Corret posi hon
ity
sed to Gonpare
steihd dject
is_reaee than
tve yale il rret bjet
ecihed object
geihed cjee
TreeSetMehod Esae
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.
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.
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
I}hethd
intodyced vergyoy
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.
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 to check if a map is having any entry for key
isEmpty()
and value pairs. If no mapping exists, then this returns true.
Mab Methody
imbort java
ah þut(lo), "vinay"):
kau "))
Mgb but (to2, "ami}"):
sop(ap);
63 = Ravi
Hash Map?
Syntax'
clas Hshma imen enh Mal
lcongue hors
orde
Hash hon Abehvon ed datn shekre
Rm renove (ie3);
le) debak , e 4 u i t .
Sygerout pvinen
APCO
Date:
Wertor1hfa Direetky
Twithoe asy Sel and
Tketr Iatefae )
inkfac
have a HoshMa
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
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):
Syykout.
bt le6 iA net
APCO
Hash tabl
WlConshuctors
ychreized d t shucture
Hayhtable
Haihtabl Bt = haw
bydeful} iiHal Gpacjty
ke
Top
igned by Jum
are
Supbeße o2 Y4U)
no
hashcode. 3
2
Bo
ht pul7, "rabQ");
APCO
Date
P'age
o
9 leg: Sachin, )?
Jo2: Yav
Difference between Hashmap and Hashtable :
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.
Hashtasle
Properties
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
Key vclit
an
ny key
o} Proehey clay
Lwith
CouYA< þvopeahey
Pregva
impoyt java il*!
imbort
Aepeches: h Prhehsl );
So.();
ouput 23
n
-APC0
Date :.
Page :
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().
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.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// 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 + "]";
}
}
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);
}
// 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:
public int compare(Object obj1, Object It compares the first object with the second
obj2) 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.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Comparator;
// 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 + "]";
}
}
// 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);
}