0% found this document useful (0 votes)
8 views53 pages

Bitwise Learning Java Unit 4

The document outlines the Java Collections Framework, detailing its components, including various interfaces such as Collection, List, Set, and Map, along with their implementations like ArrayList, LinkedList, and HashMap. It explains the advantages of using collections over traditional arrays, emphasizing dynamic sizing and built-in methods for data manipulation. Additionally, it covers core interfaces like Iterator and Collection, as well as specific classes like Stack and Queue, highlighting their operational principles and methods.

Uploaded by

deshwallucky20
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)
8 views53 pages

Bitwise Learning Java Unit 4

The document outlines the Java Collections Framework, detailing its components, including various interfaces such as Collection, List, Set, and Map, along with their implementations like ArrayList, LinkedList, and HashMap. It explains the advantages of using collections over traditional arrays, emphasizing dynamic sizing and built-in methods for data manipulation. Additionally, it covers core interfaces like Iterator and Collection, as well as specific classes like Stack and Queue, highlighting their operational principles and methods.

Uploaded by

deshwallucky20
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

W I

I T S

E
OBJECT ORIENTED E

G
A R N
N I

T W I
PROGRAMMING WITH JAVA
I S

E
(BCS-403)

Unit-IV: Java Collections Framework


L E

G
A R I N
CompleteN Notes
OOPS WITH JAVA (BCS-403)

UNIT 4 - SYLLABUS
T W I
I S
Java Collections Framework: Collection in Java, Collection Framework in Java, Hierarchy of

E
Collection Framework, Iterator Interface, Collection Interface, List Interface, ArrayList,
LinkedList, Vector, Stack, Queue Interface, Set Interface, HashSet, LinkedHashSet, SortedSet
Interface, TreeSet, Map Interface, HashMap Class, LinkedHashMap Class, TreeMap Class,
Hashtable Class, Sorting, Comparable Interface, Comparator Interface, Properties Class in
Java
E
L

G
A R N
N I

2
OOPS WITH JAVA (BCS-403)

Collection and Collection Framework in Java

WhatTis aW I
Collection?
I S
In Java, a Collection is a single dynamic object that represents a group of individual objects (elements)

E
as a single unit.
The Array Limitation: Traditional Arrays have a fixed size. Once created (e.g., int[] arr = new int),
you cannot increase or shrink their size at runtime. If the array is full, data is lost; if half-empty,
memory is wasted. Arrays also lack built-in methods for data manipulation.
The Collection Solution: Collections are Dynamic Data Structures. They grow and shrink

G
automatically as per requirement. They provide ready-made methods for operations like
E
A
searching, sorting, insertion, and deletion. N
R N I
Data Type/Wrapper Classes Rule: Collections strictly store Objects (Reference Types), not
primitive data types. To store primitives like int or float, Java provides Wrapper Classes (like
Integer, Float, Double) which are object-oriented alternatives to primitives.
3
OOPS WITH JAVA (BCS-403)

Collection and Collection Framework in Java

T W I Framework?
What is the Collection
S
I
Definition: The Collection Framework is a unified, ready-made architecture provided in the

E
[Link] package for representing and manipulating collections of objects.
Components: It consists of heavily optimized Interfaces (to define the structure), Classes (the
concrete implementations like ArrayList, HashSet), and Algorithms (methods for sorting and
searching).

G
E
A N
R N I

4
OOPS WITH JAVA (BCS-403)

Collection and Collection Framework in Java

T W I S
I

E
L

G
E
A N
R N I

5
OOPS WITH JAVA (BCS-403)

Hierarchy of Collection Framework

The framework is divided intoW


two distinct,
I separate hierarchies
T S
I
Iterable (Root Interface for Collections)

E
Collection (Sub-Interface)
List (Interface)→ Implemented by: ArrayList, LinkedList, Vector (Stack extends Vector).
Queue (Interface) → Implemented by: PriorityQueue, LinkedList (implements Deque too).
Set (Interface) → Implemented by: HashSet, LinkedHashSet.
SortedSet (Interface) → Implemented by: TreeSet.

G
E
Map (Separate Root Interface - DOES A I N
NOT extend Collection)
R N
Implemented by: HashMap, LinkedHashMap, Hashtable.
SortedMap (Interface) → Implemented by: TreeMap.
6
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

A. Collection Interface T W I S
I
It is the foundation of the framework. It defines the core methods that every List, Set, and Queue must

E
implement.
Core Methods: add(Object) (inserts element), addAll(Collection) (merges collections),
remove(Object), removeAll(Collection), size(), clear() (empties collection), isEmpty(), and
contains(Object) (searches element).
B. Iterator Interface
L

G
Theory: Iterator is an interface used to traverse (loop through) elements of any collection
E
sequentially. It is a universal cursor for A N
the CollectionI framework, replacing standard for loops.
R N
Core Methods:
hasNext(): Returns true if the iteration has more elements.
next(): Returns the next element in the iteration.
7
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

T WInterface
B. Iterator I
I S

E
Output

G
E
A N
R N I

8
OOPS WITH JAVA (BCS-403)

List Interface & Implementing Classes

T W I S
I
Theory: The List interface is a sub-interface of Collection. It represents an ordered sequence of

E
elements.
Rules:
Index-Based: It maintains the exact insertion order of elements. Every element is assigned a
zero-based integer index (0, 1, 2...), allowing you to precisely insert, update, or retrieve data
from a specific position using methods like get(index) and set(index, value).
Duplicates Allowed: Unlike Sets, Lists freely allow duplicate elements.
L

G
Null Values: You can insert anyEnumber of null values
N into a List.
A I
R N
Core Methods: add(element), add(index, element), remove(index), get(index), set(index, value),
indexOf(element)

9
OOPS WITH JAVA (BCS-403)

List Interface & Implementing Classes

T W I S
I

E
Output

G
E
A N
R N I

10
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface


A. ArrayList Class
T W I S
I
Internal Data Structure: ArrayList implements the List interface using a Dynamic Resizable Array

E
architecture.
Memory & Performance: Elements are stored in contiguous memory locations. Because of this
array-like structure, fetching data randomly (using index) is extremely fast (O(1)).
Insertion/Deletion Drawback: Inserting or deleting an element in the middle of an ArrayList is
slow,. This is because it requires physically shifting all the subsequent elements backward or
forward in memory to adjust the space.
L

G
Capacity Growth: You can define anEinitial capacity. Once
N the array is completely filled, Java
A I
R N
automatically creates a new array in the background, increasing the capacity by 50% of the
original size, and copies the old elements over.
Thread Safety: It is Unsynchronized (Not thread-safe), making it faster in a single-threaded
environment but risky in multi-threaded ones. 11
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

T W I S
I

E
L

G
E
A N
R N I

12
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

B. LinkedList Class T W I S
I
Internal Data Structure: Implements both the List and Deque interfaces using a Doubly Linked

E
List architecture.
Memory & Performance: Elements (nodes) are stored in non-contiguous memory locations and are
connected via next and previous pointers. Because of these extra pointers, LinkedList consumes
more memory than an ArrayList.
Insertion/Deletion Advantage: Inserting or deleting data in the middle of a LinkedList is extremely

G
fast. Unlike ArrayList, no shifting of data is required; Java simply updates the pointer links of the
E
adjacent nodes,. A N
R N I
Access Drawback: Random access (e.g., get(5)) is slow because the JVM must sequentially traverse
the list node-by-node from the beginning to reach the desired index.
Thread Safety: Like ArrayList, it is Unsynchronized (Not thread-safe).
13
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

T W I S
I

E
L

G
E
A N
R N I

14
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

C. Vector Class T W I S
I
Internal Data Structure: Vector is a legacy class that functions almost identically to ArrayList. It is

E
also backed by a dynamic resizable array.
Crucial Difference (Thread Safety): The biggest difference is that Vector is strictly Synchronized
(Thread-safe),. If multiple threads try to access a Vector simultaneously, only one thread is
allowed to access it at a time while the others wait in a blocked state.
Performance Impact: Because of this strict synchronization lock, Vector is significantly slower than
L

G
E single-threaded applications,.
ArrayList and is rarely used in modern
A N
N I capacity, it increases its size by 100%
Capacity Growth: When a Vector reaches itsRmaximum
(doubles the size), unlike ArrayList's 50% .

15
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

T W I S
I

E
Output

G
E
A N
R N I

16
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

D. Stack Class T W I S
I
Internal Data Structure: Stack is a legacy subclass that directly extends Vector.

E
Operating Principle: It implements the Last-In-First-Out (LIFO) data structure principle. Imagine a
stack of mobile phones or chairs; the last item placed on the top is the very first one you must remove.
Core LIFO Methods:
push(Object): Inserts an element exactly at the top of the stack.
pop(): Removes and returns the element currently at the top of the stack,. Throws an exception if

G
the stack is completely empty.
E
A of the stack andNreturns it without actually removing it.
peek(): Looks at the element at the top
R N I
search(Object): Searches for an element and returns its 1-based position from the top of the stack.
isEmpty(): Returns true if the stack contains no elements

17
OOPS WITH JAVA (BCS-403)

Core Interfaces: Iterator and Collection Interface

T W I S
I

E
L

G
E
A N
R N I

18
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue

T W I S
A. Theory of Queue Interface I

E
The Queue is an interface in the Java Collections Framework (located in the [Link] package) that
directly extends the Collection interface.
Operating Principle: It strictly follows the First-In-First-Out (FIFO) data structure principle.
Mechanism: Think of it like a real-world ticket line. Elements are always inserted at the Rear (end) of
the queue and are exclusively removed from the Front (beginning).
Implementation: Because Queue is an interface, it cannot be instantiated directly. To use a standard
L

G
FIFO queue in Java, we typically use Ethe LinkedList class, which implements the Queue interface.
A I N
R N (Thread-safe
Thread Safety: Standard queues are not thread-safe. operations require specific
BlockingQueue implementations)

19
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue


B. Core Methods: Exception vs. Return ValueW
T I S
I of methods for its three primary operations (Insert,
The Queue interface provides two distinct sets

E
Remove, and Examine). One set throws an exception if the operation fails (e.g., if the queue is full or
empty), while the other set safely returns a special value (like false or null).

Method that Throws Method that Returns


Operation Description
Exception Special Value

Adds an element to the Rear. If a capacity-restricted queue is full, add() throws an


Insert add(Object) offer(Object) exception, while offer() simply returns false
L

G
E
A N
I the element at the Front. If the queue is empty, remove()
R N
Removes and returns
Remove remove() poll() throws an exception, whereas poll() safely returns null

Returns the element at the Front without removing it. If empty, element() throws an
Examine element() peek()
exception, while peek() returns null.
20
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue

T W I S
I

E
L

G
E
A N
R N I

21
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue


C. PriorityQueue Class
T W I S
Theory: PriorityQueue is a concrete classI that implements the Queue interface.

E
Breaking FIFO: Unlike a standard queue, a PriorityQueue does not process elements in a pure FIFO
manner. Instead, elements are processed based on their Priority.
How Priority is Decided:
By default, it orders elements according to their Natural Ordering.
For Integers, the lowest numeric value has the highest priority and comes to the front.
For Strings, priority is determined alphabetically based on their ASCII values. For example, if
L

G
E "AKTU", and "Last", the queue will internally shuffle them
you insert "Hello", "India", "BTech",
A N I
R N
so that "AKTU" (starting with 'A') comes out first, followed by "BTech" ('B'), "Hello" ('H'), etc.
Custom Priority: You can also define custom sorting logic by passing a Comparator into the
PriorityQueue constructor during object creation.
22
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue

T W I S
I

E
L

G
E
A N
R N I

23
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue

D. Deque Interface T W I S
I
Theory: Deque (pronounced "deck") stands for Double Ended Queue. It is an interface in the Java

E
Collections Framework that directly extends the Queue interface..
Mechanism (Breaking FIFO): While a standard Queue strictly follows the First-In-First-Out (FIFO)
principle (where data is inserted at the rear and removed from the front), a Deque is much more
flexible. It allows you to insert and remove elements from both ends.
How Priority is Decided: Because Deque is an interface, it cannot be instantiated directly. In the Java

G
hierarchy, it is primarily implemented by the LinkedList and ArrayDeque classes
E
Versatility: Because LinkedList implements N
A the Deque interface, it becomes an incredibly versatile
R N I
data structure. It can be used simultaneously as a standard List, a FIFO Queue, or even a LIFO
Stack.

24
OOPS WITH JAVA (BCS-403)

Queue Interface & Priority Queue

T W I S
I

E
L

G
E
A N
R N I

25
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes


A. Deep Theory of Set Interface
T W
The Set interface is a core component of the Java Collections I S (located in the [Link] package) that directly
Framework
I
extends the Collection interface.

E
Mathematical Abstraction: It models the mathematical "set" abstraction, meaning its primary defining feature is that it
strictly prohibits duplicate elements.
Strict Rules & Key Characteristics:
No Duplicates: If you attempt to add an element that already exists in the set, the add() method simply ignores it
and returns false.
Unordered & Unindexed: Unlike a List, a standard Set does not maintain the insertion order of elements. Because
L

G
there is no indexing (0, 1, 2...), you cannotEaccess or remove elements using index-based methods like get(index) or
A N
set(index).
R N I
Null Values: Because duplicates are not allowed, a Set can contain at most one null element. Adding a second null
will be rejected.
Implementing Classes: Since Set is an interface, it cannot be instantiated directly. We must use its concrete
implementing classes: HashSet, LinkedHashSet, and TreeSet. 26
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes

T W I S
B. HashSet Class
Internal Architecture: HashSet implements Ithe Set interface and is backed internally by a Hash Table

E
(which is actually a HashMap internally).
Memory & Performance: It uses a hashing technique (generating a hash code for each object) to store
elements. This provides extremely fast, constant-time performance O(1) for basic operations like add(),
remove(), and contains().
Ordering Guarantee: It provides absolutely no guarantee of iteration order. The data is placed randomly
based on hash codes, and the order might even change over time as the collection grows.
L

G
Thread Safety: It is Unsynchronized (notE thread-safe).
A N
R N I

27
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes

T W I S
I

E
L

G
E
A N
R N I

28
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes

T W I S
C. LinkedHashSet Class
Theory: LinkedHashSet is a direct subclassI of HashSet.

E
Internal Architecture: It implements the Set interface using a combination of a Hash Table and a Doubly
Linked List.
Crucial Difference (Insertion Order): While it shares the same O(1) fast performance and "no duplicates"
rule as HashSet, the internal linked list allows it to maintain the exact insertion order of its elements.
When you iterate through a LinkedHashSet, elements are returned exactly in the order they were added.
Drawback: It is slightly slower and consumes more memory than HashSet due to the overhead of
L

G
maintaining the linked list pointers. E
A N
R N I

29
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes


D. SortedSet Interface
W I
Theory: SortedSet is a sub-interface of the SetTinterface.
I S
Purpose: It represents a set of elements that are automatically sorted in ascending (natural) order. Like a

E
regular Set, it does not allow duplicates.
Ordering: The sorting is based either on the elements' natural ordering (using the Comparable interface)
or by a custom Comparator provided when the set is created.
Special Methods (Exam Focus): Because the data is sorted, this interface introduces unique methods:
first(): Returns the lowest (first) element.

G
E
last(): Returns the highest (last) element.
N strictly less than the given element.
Athe set with Ielements
headSet(E toElement): Returns a view of
R N
tailSet(E fromElement): Returns a view of the set with elements greater than or equal to the given
element.
subSet(E from, E to): Returns a portion of the set between two elements.
30
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes

T W I S
E. TreeSet Class
I
Theory: TreeSet is the concrete class that implements the NavigableSet interface (which extends

E
SortedSet).
Internal Architecture: It is backed internally by a Red-Black Tree (a type of Self-Balancing Binary
Search Tree).
Performance: Because it actively sorts data every time an element is inserted, its basic operations take
O(log n) time, making it noticeably slower than HashSet.
Null Values Constraint: Unlike HashSet, a TreeSet does not allow null values. Attempting to insert a null
L

G
E it cannot compare null to other objects for sorting.
will throw a NullPointerException because
A N
R N I

31
OOPS WITH JAVA (BCS-403)

Set Interface & Implementing Classes

T W I S
I

E
L

G
E
A N
R N I

32
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes


[Link]
WFramework
The Map interface is a core component of the Java Collections
T I (located in the [Link] package), but it is
completely distinct from the rest. I S

E
Not a Collection: Unlike List, Set, or Queue, the Map interface does not extend the Collection interface. It forms its
own separate hierarchy.
Key-Value Pair Architecture: A Map represents a data structure that stores data in Key-Value pairs (similar to a real-
world dictionary). Every value you store is mapped to a specific, identifiable key.
Strict Rules:
Keys Must Be Unique: A Map absolutely cannot contain duplicate keys.

G
Replacement Behavior: If you attempt to use the put() method to insert a key that already exists, it will not throw
E
an error; instead, the old value is immediatelyAreplaced/updated N
with the new value.
R N I
Values Can Be Duplicated: While keys are strictly unique, multiple different keys can map to the exact same value.
Core Methods: put(K, V) (adds/updates pair), get(K) (fetches value by key), remove(K), containsKey(K),
containsValue(V), keySet() (returns a Set of all keys), values() (returns a Collection of all values), and entrySet()
(returns a Set of all key-value pairs).
33
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes


B. HashMap Class
T W
Internal Architecture: HashMap is the most widely usedIimplementation of the Map interface. It stores
S
I
its key-value pairs internally using a Hash Table.

E
Memory & Performance: Because it uses hashing, it provides highly efficient, constant-time performance
O(1) for basic operations like put() and get().
Ordering Guarantee: It provides absolutely no guarantee of iteration order. The order of elements is
randomized and may change over time.
Null Values: It allows exactly one null key and multiple null values.

L
Thread Safety: It is Unsynchronized (not thread-safe), making it fast for single-threaded applications.

G
E
A N
R N I

34
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes

T W I S
I

E
Output

G
E
A N
R N I

35
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes


C. LinkedHashMap Class
W I
T HashMap.
Theory: LinkedHashMap is a direct subclass of
I S
Internal Architecture: It implements the Map interface using a combination of a Hash Table and a

E
Doubly Linked List.
Crucial Difference (Insertion Order): While it behaves exactly like a HashMap (allowing one null key
and offering O(1) performance), the internal linked list allows it to maintain the exact, predictable
insertion order of the key-value pairs. When iterated, elements appear precisely in the order they were
inserted.

L
Performance: It is slightly slower and consumes more memory than HashMap due to the overhead of

G
E
maintaining the linked list pointers. A N
R N I

36
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes


D. TreeMap Class
T W theI NavigableMap and SortedMap interfaces.
Theory: TreeMap is a concrete class that implements
S
I
Internal Architecture: It is backed internally by a Red-Black Tree (a type of Self-Balancing Binary

E
Search Tree).
Sorting Feature: It completely ignores insertion order. Instead, it automatically sorts the Map entries
based strictly on the Keys in ascending (natural) order. You can also pass a custom Comparator to sort
the keys differently.
Performance: Because it actively sorts data upon every insertion, its performance is O(logn), making it

L
significantly slower than HashMap.

G
E
N a null key (it will throw a
Adoes NOT allow
Null Constraint: Unlike HashMap, TreeMap
R N I
NullPointerException because it cannot compare null for sorting). However, it allows multiple null
values.

37
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes

T W I S
I

E
L

G
E
A N
R N I

38
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes


E. Hashtable Class
T W I in Java 1.0 (before the modern Collections
Theory: The Hashtable class is a legacy class introduced
S
I
Framework even existed). It implements the Map interface and uses a hash table structure.

E
HashMap vs Hashtable: While Hashtable works almost identically to HashMap, it has two major, strict
differences:
Thread Safety: Hashtable is strictly Synchronized. This means it is thread-safe; only one thread can
access it concurrently. Because of this lock mechanism, it is significantly slower than the un-
synchronized HashMap.

L
No Nulls Allowed: It strictly prohibits nulls. It does NOT allow any null keys OR null values.

G
E
Attempting to insert a null will immediately N
A crash the program with a NullPointerException.
R N I

39
OOPS WITH JAVA (BCS-403)

Map Interface & Implementing Classes

T W I S
I

E
L

G
E
A N
R N I

40
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections


A. Theory
T W ofIa data
Sorting is the fundamental process of arranging elements S structure in a particular, predictable
I
sequence—typically in Ascending (Natural) order or Descending (Reverse) order.

E
The Utility Classes: While data structures like TreeSet or TreeMap sort data automatically upon
insertion, standard collections like ArrayList or LinkedList do not. To sort these unordered lists, the
Java Collections Framework provides a highly optimized, static utility class called Collections (note the
's' at the end).
Collections vs. Arrays: It is important to remember that the [Link]() method is strictly used for

G
Collection objects (like Lists). If you need to sort a standard, fixed-size Java array (e.g., int[] or String[]),
E
you must use the [Link]() utility method I N
A from the Arrays class.
R N

41
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections


B. The Two Primary Sorting Methods
T W Imethods for sorting a List:
The Collections class provides two heavily used overloaded
S
1. [Link](List<T> list)
I

E
This method sorts the elements of the given list in their Natural Order.
Natural order is predefined by Java for standard classes (e.g., Strings are sorted alphabetically
(lexicographically), and Integers are sorted numerically from smallest to largest).
2. [Link](List<T> list, Comparator<T> c)
This method is used when you want to define Custom Sorting Logic that breaks the natural order.
For example, you can use it to sort data in descending order by passing [Link](),
L

G
E
or you can define entirely custom rules A N based on their length rather than
(like sorting Strings
R N I
alphabetically).

42
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections


Example 1: Standard Sorting (Ascending & Descending)
T W I S
I

E
L

G
E
A N
R N I

43
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections


Example 2: Custom Sorting Logic (Sorting by String Length)
T W I S
I

E
L

G
E
A N
R N I

44
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections

C. Sorting User-Defined Objects


T W I
While [Link]() works perfectly forI built-in classesSlike String or Integer, it completely fails if
you try to sort a list of custom objects (e.g., a list of Student objects containing rollNo, name, and

E
marks).
Java will not know whether to sort the students by their Roll Number, their Name, or their Marks. To
solve this critical issue, Java requires the custom class to implement the Comparable interface (for a
single default sorting logic) or relies on external Comparator classes (to provide multiple sorting
options)
L

G
E
A N
R N I

45
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections


Comparable Code Example
T W I S
I

E
L

G
E
A N
R N I

46
OOPS WITH JAVA (BCS-403)

Sorting in Java Collections


Comparator Code Example
T W I S
I

E
L

G
E
A N
R N I

47
OOPS WITH JAVA (BCS-403)

Comparable vs. Comparator Interface

T W I S
Feature I Comparable Interface Comparator Interface

E
Package [Link] package [Link] package

Provides a Single sorting sequence Provides Multiple sorting sequences


Sorting Sequences
(e.g., only by Age). (e.g., Age, Name, Salary).

Must override compare(Object obj1,


Method to Override Must override compareTo(Object obj).
Object obj2).

G
Class Modification
EModifies the actual original class Does NOT modify original class. Written
(implements Comparable).N
A in an external class.
R N I
Compares this current object with Takes two completely separate objects
Reference Usage
another object. (p1, p2).

[Link](List,
Triggered by [Link](List)
ComparatorObject)
48
OOPS WITH JAVA (BCS-403)

Properties Class in Java


A. Theory
W acts
T and
The Properties class is a part of the [Link] package I as
I S a direct subclass of the Hashtable<Object,
Object> class. Because it inherits from Hashtable, it is considered a legacy class in the Java Collections

E
Framework.
Strict String Rule: While standard maps allow you to store various data types, the Properties class is
specifically designed to handle key-value pairs where both the keys and the values MUST strictly be
Strings.
Not Generic: Unlike modern collection classes (like HashMap<K, V>), the Properties class is not

G
generic. You do not need to specify angle brackets <String, String> when creating its object.
E
A N
R N I

49
OOPS WITH JAVA (BCS-403)

Properties Class in Java

B. Purpose & Persistence Feature


T W I
I
Configuration Management: In real-world enterprise S
applications, sensitive or changeable data like

B
Database URLs, Usernames, Passwords, or OS versions are never hardcoded directly into the Java

E
source code. Instead, this data is maintained externally. The Properties class is commonly used to
manage these configuration settings.
Persistence: A highly unique feature of this class is its built-in support for saving (storing) and loading
data directly to and from external text files (typically using the .properties format). It seamlessly
integrates with Java's I/O Streams (like FileInputStream or FileReader).
L

G
E
A N
R N I

50
OOPS WITH JAVA (BCS-403)

Properties Class in Java

T W I S
I

E
L

G
E
A N
R N I

51
OOPS WITH JAVA (BCS-403)

Properties Class in Java

T W I S
I

E
L

G
E
A N
R N I

52
53

You might also like