JAVA MODULE 4
1,What is the Java Collections Framework?.5Marks
The Java Collections Framework (JCF) is a unified architecture in Java used for storing, retrieving,
and manipulating groups of objects. It provides a standard set of interfaces and classes to handle
different types of collections such as List, Set, Queue, and Map.
Definition:
The Collections Framework is a set of standard interfaces, along with corresponding classes like
ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, that help in efficiently managing data.
Goals of the Collections Framework:
1. High Performance:
Implementations like dynamic arrays, linked lists, trees, and hash tables are optimized for
efficiency.
2. Uniformity & Interoperability:
All collections work in a similar way because they follow standard interfaces.
3. Easy Extensibility:
Programmers can easily extend or implement custom collections.
Purpose of Collections:
• To represent multiple values using a single object.
• Overcomes the limitations of arrays such as fixed size and storing only homogeneous data.
Main Interfaces in JCF:
• Collection – Root interface.
• List – Ordered collection (ArrayList, LinkedList).
• Set – Unique elements (HashSet, TreeSet).
• Map – Key–value pairs (HashMap, TreeMap).
• Queue – FIFO processing (PriorityQueue).
Advantages of Java Collections Framework:
• Consistent API
• Less coding effort
• Better performance
• Supports code reusability and abstraction
[Link] the hierarchy of the Collection framework.5Marks
The Java Collections Framework is organized using a well-defined hierarchy of interfaces and
classes. At the top, it begins with the Collection interface, which is then extended by various sub-
interfaces to represent different types of collections. A separate hierarchy exists for Map, since it does
not extend Collection.
1. Collection (Root Interface)
• The topmost interface in the collection hierarchy.
• Provides basic methods such as add, remove, size, iterator, etc.
2. List Interface
• Extends Collection.
• Represents an ordered collection that allows duplicates.
• Implementations:
o ArrayList
o LinkedList
o Vector
3. Set Interface
• Extends Collection.
• Represents a collection that stores unique elements (no duplicates).
• Implementations:
o HashSet
o LinkedHashSet
o TreeSet (via SortedSet)
4. SortedSet Interface
• Extends Set.
• Stores elements in sorted order.
• Implementation: TreeSet.
5. Queue Interface
• Extends Collection.
• Used for FIFO (First-In-First-Out) processing.
• Implementations:
o PriorityQueue
o LinkedList (also used as Queue/Deque)
6. Deque Interface
• Double-ended queue.
• Implementations:
o ArrayDeque
o LinkedList
Map Hierarchy (Separate from Collection)
7. Map Interface
• Maps unique keys to values (key–value pairs).
• Implementations:
o HashMap
o TreeMap
o LinkedHashMap
o WeakHashMap
8. SortedMap Interface
• Extends Map.
• Maintains keys in ascending order.
• Implementation: TreeMap.
9. [Link]
• An inner interface of Map.
• Represents a key–value pair.
Diagram (Text Form for Exams):
[Link] Collections Framework?.5Marks
The Collections Framework in Java was introduced to overcome the limitations of traditional data
handling using arrays and to provide a standard, efficient, and unified architecture for working with
groups of objects.
Reasons for the Collections Framework:
1. High Performance:
The framework provides highly efficient implementations of fundamental data structures such
as dynamic arrays, linked lists, trees, and hash tables.
2. Uniformity and Interoperability:
All collections follow a set of standard interfaces, allowing different types of collections to
work in a similar and consistent manner.
3. Easy Extensibility:
The framework allows developers to easily extend or adapt existing collections or implement
their own custom collection classes.
4. Overcomes Array Limitations:
Arrays have fixed size and can only store homogeneous data.
Collections can grow dynamically and store heterogeneous objects.
5. Improves Readability & Reduces Coding Effort:
With ready-made data structures (ArrayList, HashSet, TreeMap, etc.), programmers no longer
need to design their own structures, reducing code complexity.
[Link] the various Java Collection Classes.10Marks
Java provides several standard collection classes that implement the core interfaces of the Java
Collections Framework. These classes offer ready-made data structures such as dynamic arrays,
linked lists, hash tables, and trees.
Below are the major collection classes and their explanations:
1. AbstractCollection
• Provides skeletal implementation of the Collection interface.
• Minimizes the effort required to implement the Collection interface.
2. AbstractList
• Extends AbstractCollection.
• Provides skeletal implementation of the List interface.
• Supports index-based element operations.
3. AbstractSequentialList
• Extends AbstractList.
• Designed for collections that use sequential access (like linked lists).
• Provides methods optimized for sequential traversal.
4. LinkedList
• Implements a doubly linked list by extending AbstractSequentialList.
• Allows fast insertion and deletion.
• Implements List, Queue, and Deque interfaces.
• Allows duplicates and maintains insertion order.
5. ArrayList
• Implements a dynamic array by extending AbstractList.
• Allows fast random access using index.
• Automatically resizes as elements are added.
• Maintains insertion order and allows duplicates.
6. AbstractSet
• Extends AbstractCollection.
• Provides skeletal implementation for the Set interface.
• Ensures no duplicate elements.
7. HashSet
• Extends AbstractSet.
• Backed by a hash table (HashMap).
• Stores unique, unordered elements.
• Allows one null value.
• Offers O(1) time for add, remove, and search.
8. LinkedHashSet
• Extends HashSet.
• Maintains insertion order using a linked list running through all entries.
• Stores unique elements with predictable iteration order.
9. TreeSet
• Implements a sorted set, using a tree structure (Red-Black tree).
• Stores elements in ascending sorted order (natural or comparator-based).
• Does not allow null values.
• Offers O(log n) performance.
10. AbstractMap
• Provides skeletal implementation of the Map interface.
• Reduces effort needed to implement custom map classes.
11. HashMap
• Extends AbstractMap.
• Implements a hash table to store key–value pairs.
• Allows one null key and multiple null values.
• Does not maintain any order.
• Provides O(1) average time for get and put.
12. TreeMap
• Extends AbstractMap.
• Implements SortedMap and NavigableMap.
• Stores key–value pairs in ascending sorted order of keys.
• Backed by a Red-Black tree.
• Does not allow null keys.
13. WeakHashMap
• Extends AbstractMap.
• Uses weak references for keys.
• Automatically removes entries when the key is no longer referenced.
14. LinkedHashMap
• Extends HashMap.
• Maintains elements in the order of insertion.
• Useful for caching (e.g., LRU caches).
15. IdentityHashMap
• Extends AbstractMap.
• Uses reference equality (==) instead of equals() to compare keys.
• Stores key–value pairs where reference comparison is important.
[Link] are the advantages of the Java Collection Framework.5Marks
The Java Collection Framework offers several important advantages that make data storage and
manipulation easier, faster, and more efficient.
1. Consistent API
All collection classes (like ArrayList, LinkedList, HashSet) implement common interfaces such as List,
Set, and Map, so methods like add(), remove(), size(), contains() work uniformly across different
collections.
2. Less Coding Effort
Developers do not need to create their own data structures.
Ready-made structures like ArrayList, HashMap, TreeSet reduce the amount of code required and
support object-oriented abstraction.
3. Better Performance
The framework provides high-performance implementations of data structures such as dynamic
arrays, linked lists, hash tables, and trees.
Operations like insertion, deletion, and search are optimized.
4. Reusability and Flexibility
Collections allow reuse of code and make it easy to switch between different implementations (e.g.,
HashSet → TreeSet) without changing program logic.
5. Improves Program Quality
By using well-tested, standardized classes, the resulting programs are more reliable, maintainable,
and easier to read.
[Link] the Array List with Key characteristics, syntax, and the constructors used.5Marks
ArrayList – Key Characteristics, Syntax, and Constructors (5 Marks)
ArrayList is a part of the Java Collections Framework and is a resizable array implementation of the
List interface. Unlike arrays, its size grows and shrinks dynamically.
Key Characteristics of ArrayList:
1. Dynamic Size:
Automatically grows or shrinks when elements are added or removed.
2. Maintains Insertion Order:
Elements are stored in the same order in which they are inserted.
3. Fast Random Access:
Provides quick access to elements using their index (like arrays).
4. Allows Null Values:
Supports storing null elements.
5. Not Thread-Safe:
It is not synchronized, so manual synchronization is needed in multithreaded environments.
Syntax:
import [Link];
ArrayList<Type> list = new ArrayList<>();
Example:
ArrayList<String> list = new ArrayList<>();
Constructors Used in ArrayList:
1. ArrayList()
o Creates an empty ArrayList with an initial capacity of 10.
Example:
2. ArrayList<Integer> list = new ArrayList<>();
3. ArrayList(int initialCapacity)
o Creates an ArrayList with the specified initial capacity.
Example:
4. ArrayList<String> names = new ArrayList<>(20);
5. ArrayList(Collection<? extends E> c)
o Creates an ArrayList initialized with all elements from the given collection.
Example:
6. ArrayList<String> newList = new ArrayList<>(oldList);
[Link] the various methods of the Array List and demonstrate itsworking with example
program.10Marks
ArrayList is a resizable array implementation of the List interface in Java. It provides many built-in
methods to add, retrieve, update, delete, and search elements efficiently.
1. Various Methods of ArrayList
1) add(E e)
Adds the specified element to the end of the list.
2) add(int index, E element)
Inserts an element at a specific index.
3) get(int index)
Returns the element at the given index.
4) set(int index, E element)
Replaces the element at a specific index.
5) remove(int index)
Removes the element at the specified index.
6) remove(Object o)
Removes the first occurrence of the specified object.
7) clear()
Removes all elements from the list.
8) contains(Object o)
Returns true if the list contains the given element.
9) indexOf(Object o)
Returns the index of the first occurrence of the element.
10) lastIndexOf(Object o)
Returns the last occurrence index of the given element.
11) isEmpty()
Checks if the list is empty.
12) size()
Returns the number of elements in the list.
13) toArray()
Returns an array containing all elements of the list.
14) subList(int fromIndex, int toIndex)
Returns a portion of the list between two indexes.
15) sort(Comparator<? super E> c)
Sorts the list according to the provided comparator.
16) iterator()
Returns an iterator over the elements.
17) listIterator()
Returns a list iterator for the list.
18) addAll(Collection<? extends E> c)
Adds all elements from another collection.
19) removeAll(Collection<?> c)
Removes all matching elements.
20) retainAll(Collection<?> c)
Retains only elements present in the given collection.
21) removeIf(Predicate<? super E> filter)
Removes all elements satisfying a condition.
22) stream()
Returns a stream for functional programming.
23) forEach(Consumer<? super E> action)
Performs an action for each element.
Output:
Fruits List: [Apple, Banana, Mango]
After adding Orange at index 1: [Apple, Orange, Banana, Mango]
Element at index 2: Banana
After removing Banana: [Apple, Orange, Mango]
Index of Mango: 2
Does the list contain Apple? true
After replacing Mango with Pineapple: [Apple, Orange, Pineapple]
Size of the list: 3
Is the list empty? false
List after clearing: []
2. Example Program Demonstrating ArrayList Working
[Link] the LinkedList with Key characteristics, syntax, and the constructors used.5Marks
LinkedList is a part of the Java Collections Framework and implements the List and Deque
interfaces. It is based on a doubly linked list structure, where each node contains references to the
previous and next nodes.
Key Characteristics of LinkedList:
1. Doubly Linked List Structure:
Each element (node) has pointers to both previous and next nodes, allowing efficient
insertions and deletions.
2. Slower Random Access:
Elements cannot be accessed directly by index (unlike ArrayList). Access requires traversal.
3. Efficient Insertions and Deletions:
Adding or removing elements at the beginning, middle, or end is fast because only pointers
need updating.
4. Implements List, Queue, and Deque:
Can be used as a list, queue (FIFO), or double-ended queue (Deque).
5. Non-Synchronized:
Not thread-safe; needs manual synchronization in multithreaded environments.
6. Allows Duplicates and Null Values:
Supports duplicate elements and null entries.
Syntax:
import [Link];
LinkedList<Type> list = new LinkedList<>();
Example:
LinkedList<String> cities = new LinkedList<>();
Constructors of LinkedList:
1. LinkedList()
Creates an empty linked list.
Example:
LinkedList<Integer> list = new LinkedList<>();
2. LinkedList(Collection<? extends E> c)
Creates a linked list initialized with elements from another collection.
Example:
LinkedList<String> newList = new LinkedList<>(oldList);
[Link] the various methods of the Linked List and demonstrate its working with example
program10Marks
LinkedList is a part of the Java Collections Framework. It implements List, Queue, and Deque,
providing powerful operations for insertion, deletion, and retrieval.
1. Various Methods of LinkedList
1) add(E e)
Adds an element to the end of the list.
2) add(int index, E element)
Inserts an element at a specific index.
3) addAll(Collection<? extends E> c)
Adds all elements from another collection.
4) addFirst(E e)
Inserts an element at the beginning of the list.
5) addLast(E e)
Adds an element at the end (same as add()).
6) clear()
Removes all elements from the list.
7) contains(Object o)
Checks if an element exists in the list.
8) get(int index)
Returns the element at the given index.
9) getFirst()
Returns the first element in the list.
10) getLast()
Returns the last element in the list.
11) remove(int index)
Removes the element at the specified index.
12) remove(Object o)
Removes the first occurrence of the given object.
13) removeFirst()
Removes and returns the first element.
14) removeLast()
Removes and returns the last element.
15) size()
Returns the number of elements.
16) isEmpty()
Checks if the list is empty.
17) indexOf(Object o)
Returns the index of the first occurrence.
18) lastIndexOf(Object o)
Returns the index of the last occurrence.
19) peek()
Returns (but does not remove) the first element.
20) poll()
Retrieves and removes the first element.
Returns null if the list is empty.
21) offer(E e)
Adds element at the end (Queue operation).
22) toArray()
Returns the elements as an array.
2. Example Program Demonstrating LinkedList Working
Output:
Cities List: [New York, London, Paris]
After adding Tokyo and Berlin: [Tokyo, New York, London, Paris, Berlin]
First City: Tokyo
Last City: Berlin
After removing first and last cities: [New York, London, Paris]
Polled City: New York
After polling: [London, Paris]
Does the list contain London? true
Cities array: London Paris
[Link] ArrayList and Linked List. Describe the Uses of Linked List vs ArrayList .5Marks
Definition of ArrayList:
An ArrayList is a resizable array implementation of the List interface.
It stores elements in contiguous memory locations and allows fast random access using index
values.
The size grows automatically when elements are added.
Definition of LinkedList:
A LinkedList is a doubly linked list implementation of the List and Deque interfaces.
Each element is stored in a node that contains links to the previous and next nodes.
It allows efficient insertions and deletions at any position.
Uses: LinkedList vs ArrayList
1. When to use ArrayList:
• When fast access of elements using index is required.
• Best for searching operations because it supports O(1) random access.
• Suitable for applications where modifications (add/remove) are less frequent.
• Good for storing and retrieving data.
2. When to use LinkedList:
• When frequent insertions and deletions are required at the beginning, middle, or end.
• Useful for queue, deque, and stack-like operations.
• Suitable when memory is allocated non-contiguously.
• Best for applications that require shifting of elements often.
[Link] the Hashset with Key characteristics, syntax, and the constructors used. 5Marks
HashSet is a collection class that implements the Set interface and is backed by a hash table. It
stores unique elements and does not maintain any order.
Key Characteristics of HashSet:
1. Stores Unique Elements Only:
Duplicate values are not allowed.
2. Backed by Hash Table:
Uses hashing mechanism for storing and retrieving elements.
3. No Insertion Order:
Elements are stored in an unordered manner, and order may change over time.
4. Allows One Null Element:
Can store a single null value.
5. Fast Performance:
Provides O(1) average time for add, remove, and search operations.
6. Not Synchronized:
Not thread-safe; must be manually synchronized when used in multithreaded environments.
Syntax:
import [Link];
HashSet<Type> set = new HashSet<>();
Example:
HashSet<String> names = new HashSet<>();
Constructors Used in HashSet:
1. HashSet()
Creates an empty HashSet with default initial capacity (16) and load factor (0.75).
Example:
HashSet<Integer> set = new HashSet<>();
2. HashSet(int initialCapacity)
Creates a HashSet with a specified initial capacity.
Example:
HashSet<String> set = new HashSet<>(20);
3. HashSet(int initialCapacity, float loadFactor)
Creates a HashSet with a specific capacity and load factor.
Example:
HashSet<String> set = new HashSet<>(50, 0.80f);
4. HashSet(Collection<? extends E> c)
Creates a HashSet containing all elements of the given collection.
Example:
HashSet<String> newSet = new HashSet<>(oldSet);
[Link] the various methods of the Hashset and demonstrate its working with example
program.10Marks
HashSet is a part of the Java Collections Framework and implements the Set interface. It stores
unique elements using a hash table and provides fast performance for basic operations.
1. Various Methods of HashSet
1) add(E e)
Adds the specified element to the set (only if it is not already present).
2) addAll(Collection<? extends E> c)
Adds all elements from another collection to the HashSet.
3) remove(Object o)
Removes the specified element if it exists in the set.
4) clear()
Removes all elements from the HashSet.
5) contains(Object o)
Checks whether the given element is present in the set.
6) isEmpty()
Checks if the set contains no elements.
7) size()
Returns the number of elements in the HashSet.
8) iterator()
Returns an iterator to traverse elements of the HashSet.
9) clone()
Creates a shallow copy of the HashSet.
10) toArray()
Returns an array containing all elements of the set.
11) removeAll(Collection<?> c)
Removes all elements that match those in the given collection.
12) retainAll(Collection<?> c)
Retains only the elements that are present in the given collection.
Output:
Animals Set: [Dog, Cat, Horse, Cow]
After adding duplicate Dog: [Dog, Cat, Horse, Cow]
Does the set contain Cat? true
After removing Horse: [Dog, Cat, Cow]
Traversing using Iterator:
Dog
Cat
Cow
Size of HashSet: 3
After clearing: []
2. Example Program Demonstrating HashSet Working
[Link] the Treeset with Key characteristics, syntax, and the constructors used.5Marks
TreeSet is a collection class in Java that implements the SortedSet interface.
It stores elements in ascending sorted order using a balanced tree structure (Red-Black Tree).
Key Characteristics of TreeSet:
1. Stores Elements in Sorted Order:
Elements are automatically arranged in ascending (natural) order or based on a custom
comparator.
2. Unique Elements Only:
Does not allow duplicates.
3. Backed by a Red-Black Tree:
Provides efficient O(log n) time for add, remove, and search operations.
4. Does NOT Allow Null Values:
Adding null causes a NullPointerException.
5. Navigational Methods:
Supports methods like first(), last(), higher(), lower(), etc. for easy navigation.
6. Not Synchronized:
It is not thread-safe and must be manually synchronized if needed.
Syntax:
import [Link];
TreeSet<Type> ts = new TreeSet<>();
Example:
TreeSet<Integer> numbers = new TreeSet<>();
Constructors of TreeSet:
1. TreeSet()
Creates an empty TreeSet with natural ordering.
TreeSet<String> ts = new TreeSet<>();
2. TreeSet(Collection<? extends E> c)
Creates a TreeSet containing elements from the given collection.
TreeSet<Integer> ts = new TreeSet<>(list);
3. TreeSet(Comparator<? super E> comparator)
Creates a TreeSet with a custom sorting rule.
TreeSet<String> ts = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
4. TreeSet(SortedSet s)
Creates a TreeSet with the same elements and ordering as the given sorted set.
TreeSet<Integer> ts = new TreeSet<>(otherSet);
[Link] the various methods of the Treeset and demonstrate its working with example
program.10Marks
TreeSet is a part of the Java Collections Framework and implements the SortedSet and NavigableSet
interfaces.
It stores unique elements in ascending sorted order using a Red-Black Tree.
1. Various Methods of TreeSet
1) add(E e)
Adds an element to the TreeSet.
Automatically inserts according to sorted order.
2) addAll(Collection<? extends E> c)
Adds all elements from another collection.
3) remove(Object o)
Removes the specified element if it exists.
4) clear()
Removes all elements from the TreeSet.
5) first()
Returns the smallest element.
6) last()
Returns the largest element.
7) higher(E e)
Returns the next higher element (greater than e).
8) lower(E e)
Returns the next lower element (less than e).
9) ceiling(E e)
Returns the element ≥ e (or null if not found).
10) floor(E e)
Returns the element ≤ e (or null if not found).
11) contains(Object o)
Checks if an element exists in the TreeSet.
12) isEmpty()
Returns true if the TreeSet is empty.
13) size()
Returns the total number of elements.
14) iterator()
Returns an iterator to traverse the TreeSet in ascending order.
15) descendingIterator()
Traverses elements in reverse order.
16) toArray()
Returns an array holding all TreeSet elements.
17) subSet(E from, E to)
Returns a portion of the set between two elements.
18) headSet(E toElement)
Returns all elements less than the specified value.
19) tailSet(E fromElement)
Returns all elements greater than or equal to the given element.
Output:
TreeSet: [10, 20, 30, 40, 50]
First Element: 10
Last Element: 50
Higher than 30: 40
Lower than 30: 20
After removing 20: [10, 30, 40, 50]
Ascending order:
10
30
40
50
Descending order:
50
40
30
10
Size of TreeSet: 4
2. Example Program Demonstrating TreeSet Working
[Link] Hashset and Treeset. Describe the Uses of Hashset and Treeset.5Marks
Definition of HashSet:
A HashSet is a collection class in Java that implements the Set interface.
It stores unique elements using a hash table and does not maintain any order of elements.
It provides O(1) average time for add, remove, and search operations.
Definition of TreeSet:
A TreeSet is a collection class that implements the SortedSet interface.
It stores unique elements in ascending sorted order using a Red-Black Tree.
It provides O(log n) time performance for basic operations.
Uses of HashSet:
1. Fast Searching Operations
Best when quick lookup, insertion, and deletion are required.
2. Storing Unique Elements
Useful when duplicates must not be allowed.
3. Unordered Collections
Suitable when the order of elements does not matter.
4. Implementing Sets or Removing Duplicates
Often used to filter repeated values from lists.
Uses of TreeSet:
1. Maintaining Sorted Data
Ideal when elements must always remain in sorted (ascending) order.
2. Implementing Navigational Set
Provides methods like first(), last(), higher(), lower(), useful for range queries.
3. Storing Unique Elements in Order
Best for applications where ordering + uniqueness are both required.
4. Creating Ordered Collections
Useful in scenarios like ranking systems, alphabetical lists, and sorted reports.
Conclusion:
• HashSet is used for fast performance and no ordering.
• TreeSet is used for sorted and navigable collections.
[Link] Queue with Key characteristics, syntax, and the constructors used.5Marks
A Queue in Java is a collection used to store elements in a FIFO (First-In-First-Out) manner.
It is part of the Java Collections Framework and is implemented using classes such as LinkedList,
PriorityQueue, and ArrayDeque.
Key Characteristics of Queue:
1. FIFO Order:
The element inserted first is removed first (front → rear processing).
2. Supports Insertion & Deletion Operations:
o Enqueue → adding elements
o Dequeue → removing elements
3. Multiple Implementation Classes:
Common implementations include:
o LinkedList
o PriorityQueue
o ArrayDeque
4. Does Not Allow Random Access:
Elements are accessed only from the front or rear, not via index.
5. Useful for Scheduling & Buffering:
Ideal for tasks like CPU scheduling, print queue, and message handling.
6. May Allow Null (but PriorityQueue does not):
Allowance of null depends on implementation.
Syntax:
Queue<Type> queue = new LinkedList<>();
Example:
Queue<Integer> q = new LinkedList<>();
Constructors (From Implementing Classes):
1. LinkedList() Constructor
Used to create a Queue backed by LinkedList.
Queue<String> q = new LinkedList<>();
2. PriorityQueue() Constructor
Creates an empty PriorityQueue with natural ordering.
Queue<Integer> pq = new PriorityQueue<>();
3. PriorityQueue(int initialCapacity)
Creates a PriorityQueue with specified initial capacity.
Queue<Integer> pq = new PriorityQueue<>(20);
4. ArrayDeque() Constructor
Creates a resizable-array based queue.
Queue<String> ad = new ArrayDeque<>();
[Link] the PriorityQueue with Key characteristics, syntax, and the constructors used. 5Marks
PriorityQueue is a class in the Java Collections Framework that implements the Queue interface.
It arranges its elements according to their priority, where the head of the queue is always the lowest
or highest priority element depending on the comparator used.
Key Characteristics of PriorityQueue:
1. Priority-Based Ordering:
Elements are ordered based on natural ordering (ascending) or a custom comparator.
2. Not FIFO:
Unlike a normal queue, removal is based on priority, not insertion time.
3. No Null Elements:
PriorityQueue does not allow null values.
4. Unbounded but Growing:
It is logically unbounded but expands automatically when elements increase.
5. Not Thread-Safe:
It is not synchronized, so it must be manually synchronized in multithreaded environments.
6. Backed by a Heap Structure:
Internally uses a binary heap for efficient priority-based access.
Syntax:
PriorityQueue<Type> pq = new PriorityQueue<>();
Example:
PriorityQueue<Integer> pq = new PriorityQueue<>();
Constructors Used in PriorityQueue:
1. PriorityQueue()
Creates an empty priority queue with natural ordering.
PriorityQueue<String> pq = new PriorityQueue<>();
2. PriorityQueue(int initialCapacity)
Creates a PriorityQueue with the specified initial capacity.
PriorityQueue<Integer> pq = new PriorityQueue<>(20);
3. PriorityQueue(int initialCapacity, Comparator<? super E> comparator)
Creates a PriorityQueue with custom ordering.
PriorityQueue<Integer> pq = new PriorityQueue<>(10, [Link]());
4. PriorityQueue(Collection<? extends E> c)
Creates a PriorityQueue containing elements from the given collection.
PriorityQueue<String> pq = new PriorityQueue<>(list);
[Link] the various methods of the PriorityQueue and demonstrate its working with example
program.10Marks
A PriorityQueue is a queue that arranges elements according to their priority.
By default, elements are ordered in natural ascending order, and the head of the queue is the lowest
element.
1. Various Methods of PriorityQueue
1) add(E e)
Inserts the element into the priority queue.
If capacity is full, an exception is thrown.
2) offer(E e)
Adds the element; returns true or false instead of throwing exceptions.
3) peek()
Returns (but does not remove) the head element (highest priority).
Returns null if the queue is empty.
4) element()
Returns the head element but throws an exception if queue is empty.
5) poll()
Retrieves and removes the head element.
Returns null if the queue is empty.
6) remove()
Removes the head element and throws exception if queue is empty.
7) remove(Object o)
Removes the specified element from the queue.
8) contains(Object o)
Checks if the queue contains the given element.
9) size()
Returns the number of elements in the queue.
10) isEmpty()
Checks whether the queue is empty.
11) clear()
Removes all elements from the queue.
12) toArray()
Converts the queue elements into an array.
13) iterator()
Returns an iterator to traverse the queue elements (not in sorted order).
14) comparator()
Returns the comparator used for ordering, or null for natural order.
Output:
PriorityQueue: [10, 20, 50, 30]
Head of the queue (peek): 10
Removed element (poll): 10
PriorityQueue after poll: [20, 30, 50]
After offering 40: [20, 30, 50, 40]
Does queue contain 20? true
Iterating Queue:
20
30
50
40
Size of PriorityQueue: 4
After clearing: []
2. Example Program Demonstrating PriorityQueue Working
[Link] Queue and PriorityQueue. Describe the Uses of the Queueand Use cases of
PriorityQueue.5Marks
Definition of Queue:
A Queue is a linear data structure that stores elements in the FIFO (First-In-First-Out) order.
The element inserted first is removed first.
It is commonly implemented using LinkedList, ArrayDeque, or PriorityQueue.
Definition of PriorityQueue:
A PriorityQueue is a special type of queue where elements are arranged based on priority.
The head of the queue contains the element with the highest priority (by default, the smallest value).
It is implemented using a binary heap.
Uses of Queue:
1. Task Scheduling (CPU Scheduling)
Processes are handled in the order they arrive.
2. Operating System Queues
Used in job queues, ready queues, and device queues.
3. Printing Tasks
Print jobs are executed in the order they are added.
4. Message Passing & Buffering
Used in communication systems and data streaming.
5. Breadth-First Search (BFS)
Queue is essential in graph level-order traversal.
Use Cases of PriorityQueue:
1. Handling Tasks by Priority
Higher-priority tasks are executed before lower-priority ones.
2. Dijkstra’s Algorithm
Used in shortest path computations in graph algorithms.
3. Huffman Coding
Used to build optimal prefix trees.
4. Job Scheduling
Tasks with the highest priority (lowest time/weight) are executed first.
5. Real-Time Simulations
Events are processed in priority order.
[Link] the HashMap with Key characteristics, syntax, and the constructor used. 5Marks
HashMap is a class in the Java Collections Framework that implements the Map interface.
It stores data in the form of key–value pairs and uses a hash table for fast access.
Key Characteristics of HashMap:
1. Stores Key–Value Pairs:
Each value is associated with a unique key.
2. No Duplicate Keys:
Keys must be unique, but values can be duplicated.
3. Allows One Null Key and Multiple Null Values:
Supports storing null.
4. Unordered Collection:
Does not maintain insertion order; elements are stored based on hash values.
5. Fast Performance:
Provides average O(1) time for insertion, deletion, and search.
6. Not Synchronized:
It is not thread-safe; must be synchronized manually for multithreading.
7. Backed by Hash Table + Linked List / Tree (Java 8+):
Uses bucket mechanism for efficient access.
Syntax:
import [Link];
HashMap<KeyType, ValueType> map = new HashMap<>();
Example:
HashMap<Integer, String> map = new HashMap<>();
Constructors Used in HashMap:
1. HashMap()
Creates an empty HashMap with default capacity (16) and load factor (0.75).
HashMap<String, Integer> map = new HashMap<>();
2. HashMap(int initialCapacity)
Creates a HashMap with a specific initial capacity.
HashMap<Integer, String> map = new HashMap<>(20);
3. HashMap(int initialCapacity, float loadFactor)
Creates a HashMap with custom capacity and load factor.
HashMap<String, String> map = new HashMap<>(50, 0.80f);
4. HashMap(Map<? extends K, ? extends V> m)
Creates a HashMap containing all key–value pairs from another map.
HashMap<Integer, String> newMap = new HashMap<>(oldMap);
[Link] the various methods of the HashMap and demonstrate its working with example
program.10Marks
HashMap is a class in the Java Collections Framework that stores key–value pairs using a hash
table.
It allows fast retrieval, insertion, and deletion using hashing.
1. Various Methods of HashMap
1) put(K key, V value)
Adds a key–value pair into the HashMap.
If the key already exists, its value is replaced.
2) putIfAbsent(K key, V value)
Adds the value only if the key is not already present.
3) get(Object key)
Returns the value associated with the specified key.
4) getOrDefault(Object key, V defaultValue)
Returns the value if key exists; otherwise returns the default value.
5) remove(Object key)
Removes the key–value pair corresponding to the specified key.
6) remove(Object key, Object value)
Removes only if both key and value match.
7) containsKey(Object key)
Checks if a key exists in the HashMap.
8) containsValue(Object value)
Checks if a value exists in the HashMap.
9) keySet()
Returns a set of all keys in the map.
10) values()
Returns a collection of all values.
11) entrySet()
Returns a set of key–value pairs ([Link] objects).
12) size()
Returns the number of key–value pairs in the map.
13) isEmpty()
Checks whether the map is empty.
14) clear()
Removes all key–value pairs from the HashMap.
15) replace(K key, V value)
Replaces the value of the specified key.
16) putAll(Map<? extends K, ? extends V> m)
Copies all entries from another map.
17) clone()
Creates a shallow copy of the HashMap.
Output:
Students Map: {101=Anushree, 102=Rahul, 103=Megha}
Name with ID 102: Rahul
Contains key 103? true
After replacing value of key 103: {101=Anushree, 102=Rahul, 103=Meena}
After removing key 101: {102=Rahul, 103=Meena}
Displaying all key-value pairs:
102 -> Rahul
103 -> Meena
Size of HashMap: 2
After clearing: {}
2. Example Program Demonstrating HashMap Working
[Link] the TreeMap with Key characteristics, syntax, and the constructors used.5Marks
TreeMap is a class in the Java Collections Framework that implements the NavigableMap and
SortedMap interfaces.
It stores key–value pairs in ascending sorted order of keys using a Red-Black Tree.
Key Characteristics of TreeMap:
1. Stores Keys in Sorted Order:
All keys are automatically arranged in ascending (natural) order or according to a custom
comparator.
2. No Duplicate Keys:
Keys must be unique, but values can be duplicated.
3. Does NOT Allow Null Keys:
Adding a null key results in a NullPointerException (values can be null).
4. Backed by a Red-Black Tree:
Provides O(log n) time complexity for insertion, deletion, and searching.
5. Navigational Methods:
Supports methods like firstKey(), lastKey(), higherKey(), lowerKey() for easy navigation.
6. Not Synchronized:
TreeMap is not thread-safe and must be synchronized manually if used in multithreading.
Syntax:
import [Link];
TreeMap<KeyType, ValueType> map = new TreeMap<>();
Example:
TreeMap<Integer, String> tm = new TreeMap<>();
Constructors Used in TreeMap:
1. TreeMap()
Creates an empty TreeMap with natural ordering of keys.
TreeMap<String, Integer> tm = new TreeMap<>();
2. TreeMap(Comparator<? super K> comparator)
Creates a TreeMap with a custom ordering of keys.
TreeMap<String, Integer> tm = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
3. TreeMap(Map<? extends K, ? extends V> m)
Creates a TreeMap containing all entries from another map, sorted by keys.
TreeMap<Integer, String> tm = new TreeMap<>(otherMap);
4. TreeMap(SortedMap<K, ? extends V> m)
Creates a TreeMap with the same ordering and elements as the given SortedMap.
TreeMap<Integer, String> tm = new TreeMap<>(sortedMap);
[Link] the various methods of the TreeMap and demonstrate its working with example
program.10Marks
TreeMap is a part of the Java Collections Framework and implements SortedMap and NavigableMap.
It stores key–value pairs in ascending sorted order of keys using a Red-Black Tree.
1. Various Methods of TreeMap
1) put(K key, V value)
Adds a key–value pair to the TreeMap.
If the key exists, its value is replaced.
2) putIfAbsent(K key, V value)
Inserts the key–value pair only if the key is not already present.
3) get(Object key)
Returns the value associated with the given key.
4) getOrDefault(Object key, V defaultValue)
Returns the value of the key if present, otherwise returns the default value.
5) remove(Object key)
Removes the mapping for the specified key.
6) remove(Object key, Object value)
Removes the entry only if key and value match.
7) containsKey(Object key)
Checks if the key is present.
8) containsValue(Object value)
Checks if the value exists in the map.
9) firstKey()
Returns the smallest key.
10) lastKey()
Returns the largest key.
11) higherKey(K key)
Returns the key strictly greater than the given key.
12) lowerKey(K key)
Returns the key strictly smaller than the given key.
13) ceilingKey(K key)
Returns the key ≥ given key.
14) floorKey(K key)
Returns the key ≤ given key.
15) keySet()
Returns a set of all keys in sorted order.
16) values()
Returns a collection of all values.
17) entrySet()
Returns all key–value pairs as [Link] objects.
18) size()
Shows the number of entries.
19) isEmpty()
Checks if the TreeMap is empty.
20) clear()
Removes all the entries from the TreeMap.
Output:
TreeMap: {1=Anushree, 2=Megha, 3=Rahul, 4=Ragini, 5=Karan}
Student with roll 2: Megha
First Key: 1
Last Key: 5
Higher than 3: 4
Lower than 3: 2
After removing roll 4: {1=Anushree, 2=Megha, 3=Rahul, 5=Karan}
Displaying all entries:
1 -> Anushree
2 -> Megha
3 -> Rahul
5 -> Karan
Size of TreeMap: 4
After clearing: {}
2. Example Program Demonstrating TreeMap Working
[Link] HashMap and TreeMap. Describe the Use cases of the HashMap and TreeMap.5Marks
Definition of HashMap:
A HashMap is a class in the Java Collections Framework that stores data in the form of key–value
pairs.
It uses a hash table for storing entries, which allows fast insertion, deletion, and searching.
It does not maintain any order of keys and allows one null key and multiple null values.
Definition of TreeMap:
A TreeMap is a class that implements the SortedMap and NavigableMap interfaces.
It stores key–value pairs in ascending sorted order of keys using a Red-Black Tree.
It does not allow null keys, but values can be null.
Use Cases of HashMap:
1. Fast Search Operations
Used when quick access to values based on keys is required.
2. Storing Unique Keys with Values
Ideal for maintaining user data, student records, and product details.
3. Implementing Caches
Frequently used for caching where data retrieval must be fast.
4. Removing Duplicates
Eliminating repeated values by storing them as keys.
Use Cases of TreeMap:
1. Maintaining Sorted Data
Useful when keys must remain sorted automatically (e.g., roll numbers, names).
2. Range-Based Operations
Methods like higherKey(), lowerKey(), firstKey(), and lastKey() help in navigation.
3. Building Ordered Maps
Helpful in applications requiring alphabetical order or rankings.
4. Implementing Balanced Search Trees
Suitable for tasks that need predictable ordering and log-time access.
[Link] Generic Classes and Methods with the syntax 5Marks
Generic Classes:
A Generic Class in Java is a class that can operate on different data types using a single class
definition.
It uses type parameters (like <T>, <E>, <K, V>) to make the class reusable, type-safe, and flexible.
Advantages:
• Ensures type safety
• Reduces type-casting
• Enables code reusability
Syntax of a Generic Class:
Example:
GenericClass<Integer> obj = new GenericClass<>(10);
Generic Methods:
A Generic Method is a method that declares its own type parameter(s), allowing it to work with
different data types.
Advantages:
• Same method works for multiple data types
• Provides compile-time type checking
Syntax of a Generic Method:
public <T> void display(T value) {
[Link](value);
Example:
display(10);
display("Anushree");
[Link] the java program to demonstrate Generic Classes and Methods. 10,Marks