Module 1
What is Collection Framework? Explain any four methods
defined by the Collection Interface.
Collection Framework
The Java Collections Framework (JCF) is a unified architecture that provides a set of
interfaces and classes to store, manipulate, and process groups of objects efficiently. It contains
ready-made implementations of data structures such as List, Set, Queue, and Map. It reduces
programming effort and improves performance through optimized algorithms.
Advantages
1. Provides ready-made data structures.
2. Reduces coding effort.
3. Improves efficiency and performance.
4. Supports reusable and maintainable code.
Collection Framework Hierarchy
Collection
/ | \
List Set Queue
Four Methods of Collection Interface
1. add(E e)
Adds the specified element to the collection.
Syntax:
add(element);
2. remove(Object o)
Removes the specified element from the collection.
Syntax:
remove(element);
3. size()
Returns the number of elements present in the collection.
Syntax:
size();
4. isEmpty()
Checks whether the collection is empty.
Syntax:
isEmpty();
Conclusion
The Java Collections Framework provides a standard way of storing and manipulating data. The
methods add(), remove(), size(), and isEmpty() are commonly used operations provided by
the Collection interface for managing collections efficiently.
Concept Explanation (Learning Mode)
i) Queue Interface
What is a Queue?
A Queue is a collection interface used to store elements in FIFO (First In First Out) order. This
means the element inserted first is removed first, just like a queue of people standing at a ticket
counter.
Real-Life Example
Front ← [A] [B] [C] ← Rear
Remove A first
A entered first, so A leaves first.
Important Characteristics
● Follows FIFO principle.
● Allows insertion at the rear.
● Allows deletion from the front.
● Implemented by classes such as:
○ PriorityQueue
○ ArrayDeque
○ LinkedList
Common Methods
add()
Adds an element to the queue.
[Link](10);
offer()
Inserts an element into the queue.
[Link](20);
peek()
Returns the front element without removing it.
int x = [Link]();
poll()
Returns and removes the front element.
int x = [Link]();
ii) SortedSet Interface
What is SortedSet?
A SortedSet is a sub-interface of the Set interface that stores elements in sorted order
automatically. It does not allow duplicate elements. The most common implementation of
SortedSet is TreeSet.
Example
Suppose we insert:
50, 10, 30, 20
TreeSet automatically stores:
10, 20, 30, 50
Important Characteristics
● Elements are automatically sorted.
● Duplicate elements are not allowed.
● Provides navigation methods.
● Implemented by TreeSet.
Common Methods
first()
Returns the first element.
int first = [Link]();
last()
Returns the last element.
int last = [Link]();
headSet()
Returns elements before a specified element.
[Link](50);
tailSet()
Returns elements after a specified element.
[Link](20);
Queue vs SortedSet
Queue SortedSet
FIFO order Sorted order
Duplicates allowed Duplicates not allowed
Queue interface Set sub-interface
Example: PriorityQueue Example: TreeSet
2) Explain the following collection interfaces:
i) Queue Interface
The Queue interface is a part of the Java Collections Framework used to store and access
elements in First In First Out (FIFO) order. Elements are inserted at the rear and removed from
the front. It is commonly used in scheduling and buffering applications.
Features
1. Follows FIFO principle.
2. Supports insertion and deletion operations.
3. Implemented by PriorityQueue, ArrayDeque, and LinkedList.
4. Useful for task scheduling and message handling.
Important Methods
[Link](10); // insert element
[Link](20); // insert element
[Link](); // view front element
[Link](); // remove front element
Diagram
Front ← [10] [20] [30] ← Rear
ii) SortedSet Interface
The SortedSet interface is a sub-interface of the Set interface that stores elements in sorted
order and does not allow duplicate elements. TreeSet is the most common implementation of
SortedSet.
Features
1. Maintains elements in ascending order.
2. Does not allow duplicate elements.
3. Provides navigation methods.
4. Implemented by TreeSet.
Important Methods
[Link](); // first element
[Link](); // last element
[Link](50); // elements before 50
[Link](20); // elements after 20
Example
TreeSet<Integer> set = new TreeSet<>();
[Link](50);
[Link](10);
[Link](30);
[Link](set);
Output
[10, 30, 50]
Conclusion
Queue is used for FIFO processing of elements, whereas SortedSet stores unique elements in
automatically sorted order. Both are important interfaces of the Java Collections Framework.
3) Demonstrate ArrayList Class for Collection with an
Example.
Definition
ArrayList is a class of the Java Collections Framework that implements the List interface. It
provides a dynamic array whose size can be increased or decreased automatically. It maintains
insertion order and allows duplicate elements.
Features of ArrayList
1. Dynamic and resizable array.
2. Implements List interface.
3. Maintains insertion order.
4. Allows duplicate elements.
5. Provides fast random access using indexes.
6. Supports various methods such as add(), get(), set(), remove(), and size().
Common Methods
[Link]("Java"); // Add element
[Link](0); // Access element
[Link](1,"Python"); // Modify element
[Link](0); // Remove element
[Link](); // Number of elements
Example Program
import [Link];
class Main {
public static void main(String[] args) {
ArrayList<String> languages = new ArrayList<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link]("ArrayList: " + languages);
String lang = [Link](1);
[Link]("Element at index 1: " + lang);
[Link](2, "JavaScript");
[Link]("Modified ArrayList: " + languages);
[Link](0);
[Link]("Updated ArrayList: " + languages);
Output
ArrayList: [Java, Python, C++]
Element at index 1: Python
Modified ArrayList: [Java, Python, JavaScript]
Updated ArrayList: [Python, JavaScript]
Conclusion
ArrayList is one of the most widely used classes in the Java Collections Framework. It provides
the functionality of a dynamic array and allows easy insertion, deletion, modification, and
retrieval of elements.
Important Viva Question
Q: Why do we use Integer instead of int in ArrayList?
ArrayList<Integer> numbers = new ArrayList<>();
Because ArrayList stores objects, not primitive data types. Therefore, wrapper classes such as
Integer, Double, and Character are used instead of int, double, and char.
One thing first:
⚠️ HashMap and TreeMap are NOT present in the module you uploaded.
Your module explains:
● Collection Interface
● ArrayList
● LinkedList
● HashSet
● LinkedHashSet
● TreeSet
● PriorityQueue
● ArrayDeque
● User-defined classes
● RandomAccess Interface
But since your question explicitly asks HashMap and TreeMap, it is probably from your syllabus
and can still be asked in exams.
4) Explain the following Map Classes:
i) HashMap
HashMap is a class of Java Collections Framework that implements the Map interface and
stores data in key-value pairs. It uses a hash table for storage and provides fast insertion,
deletion, and retrieval operations.
Features
1. Stores data in key-value pairs.
2. Keys are unique.
3. Values can be duplicated.
4. Does not maintain insertion order.
5. Provides fast access to data.
Important Methods
[Link](101,"Anish");
[Link](101);
[Link](101);
[Link](101);
Example
HashMap<Integer,String> map = new HashMap<>();
[Link](101,"Anish");
[Link](102,"Rahul");
[Link](map);
Output:
{101=Anish, 102=Rahul}
ii) TreeMap
TreeMap is a class that implements the Map interface and stores key-value pairs in sorted order
of keys. It internally uses a Red-Black Tree.
Features
1. Stores key-value pairs.
2. Maintains sorted order of keys.
3. Keys are unique.
4. Values can be duplicated.
5. Supports navigation operations.
Important Methods
[Link](101,"Anish");
[Link](101);
[Link]();
[Link]();
Example
TreeMap<Integer,String> map = new TreeMap<>();
[Link](103,"Priya");
[Link](101,"Anish");
[Link](102,"Rahul");
[Link](map);
Output:
{101=Anish, 102=Rahul, 103=Priya}
Difference Between HashMap and TreeMap
HashMap TreeMap
Does not maintain order Maintains sorted order
Uses Hash Table Uses Red-Black Tree
Faster Comparatively slower
Suitable for fast retrieval Suitable for sorted data
5) Explain how to use and store user-defined classes in
collections.
Definition
User-defined classes can be stored in Java collections just like built-in classes such as String
and Integer. Collections such as ArrayList, HashSet, and HashMap can hold objects of custom
classes created by the programmer.
Steps to Store User-Defined Classes in Collections
Step 1: Define a User-Defined Class
class Person {
String name;
int age;
Person(String name, int age) {
[Link] = name;
[Link] = age;
}
public String toString() {
return name + " " + age;
}
}
Step 2: Store Objects in an ArrayList
ArrayList<Person> people = new ArrayList<>();
[Link](new Person("John",30));
[Link](new Person("Alice",25));
[Link](new Person("Bob",35));
Step 3: Display Objects
for(Person p : people) {
[Link](p);
}
Output:
John 30
Alice 25
Bob 35
Using User-Defined Classes with HashSet
HashSet<Person> peopleSet = new HashSet<>();
[Link](new Person("John",30));
[Link](new Person("Alice",25));
Using User-Defined Classes with HashMap
HashMap<String,Person> personMap = new HashMap<>();
[Link]("john123",
new Person("John",30));
Here:
Key -> String
Value -> Person Object
Advantages
1. Stores complex data efficiently.
2. Organizes related information into objects.
3. Can be used with ArrayList, HashSet, HashMap, Queue, etc.
4. Improves code reusability and maintainability.
Conclusion
Java collections can store objects of user-defined classes in the same way as built-in objects.
Collections such as ArrayList, HashSet, and HashMap provide an efficient way to manage
custom objects in Java applications.
6) Mention any four legacy methods defined by Vector.
Vector is a legacy class in Java that implements the List interface and provides dynamic array
functionality. It contains several legacy methods for backward compatibility.
Four Legacy Methods of Vector
1. addElement()
Adds an element to the end of the vector.
[Link]("Java");
2. elementAt()
Returns the element present at the specified index.
String s = [Link](0);
3. firstElement()
Returns the first element of the vector.
String first = [Link]();
4. lastElement()
Returns the last element of the vector.
String last = [Link]();
Summary Table
Method Description
addElement() Adds an element to the vector
elementAt() Returns element at specified index
firstElement() Returns first element
lastElement() Returns last element
Conclusion
The legacy methods of Vector provide operations for inserting, accessing, and managing
elements. Commonly used legacy methods include addElement(), elementAt(), firstElement(),
and lastElement().
Easy Exam Memory Trick
Think:
addElement()
elementAt()
firstElement()
lastElement()
These four are the most frequently asked Vector legacy methods in university exams.
7) Explain how collections can be accessed using an
iterator with example.
Definition
The Iterator interface is used to traverse or access elements of a collection one by one. It
provides methods that enable sequential access to collection elements.
Methods of Iterator
1. hasNext()
Checks whether another element is available in the collection.
[Link]();
Returns true if a next element exists.
2. next()
Returns the next element in the collection.
[Link]();
3. remove()
Removes the current element from the collection.
[Link]();
Example Program
import [Link];
import [Link];
class Main {
public static void main(String[] args) {
ArrayList<String> animals = new ArrayList<>();
[Link]("Cat");
[Link]("Dog");
[Link]("Cow");
Iterator<String> itr = [Link]();
while([Link]()) {
[Link]([Link]());
}
}
}
Output
Cat
Dog
Cow
Working
1. iterator() creates an Iterator object.
2. hasNext() checks whether another element exists.
3. next() retrieves the next element.
4. The loop continues until all elements are accessed.
Diagram
Iterator
↓
[Cat, Dog, Cow]
next() → Cat
next() → Dog
next() → Cow
Conclusion
The Iterator interface provides a simple and efficient way to traverse collection elements
sequentially using methods such as hasNext() and next(). It can be used with collections
like ArrayList, HashSet, LinkedHashSet, and TreeSet.
⚠️ Important: This question is only partially related to your module.
Your module explicitly mentions Vector as a legacy collection indirectly through the
RandomAccess section, but it doesn’t fully explain all legacy classes. However, university
exams often ask this question from standard Java Collections Framework theory.
8) What are Legacy Classes? Explain different Legacy
Classes with a Java Program.
Definition
Legacy classes are the collection classes that existed before the introduction of the Java
Collections Framework in JDK 1.2. These classes were later integrated into the Collections
Framework to provide backward compatibility.
Different Legacy Classes
1. Vector
● Dynamic array implementation.
● Maintains insertion order.
● Allows duplicate elements.
● Synchronized and thread-safe.
Vector<String> v = new Vector<>();
[Link]("Java");
[Link]("Python");
2. Stack
● Extends Vector.
● Follows LIFO principle.
Stack<Integer> stack = new Stack<>();
[Link](10);
[Link](20);
[Link]([Link]());
3. Hashtable
● Stores key-value pairs.
● Keys are unique.
● Does not allow null key or value.
Hashtable<Integer,String> ht = new Hashtable<>();
[Link](1,"Java");
[Link](2,"Python");
4. Dictionary
● Abstract class for storing key-value pairs.
● Parent class of Hashtable.
Methods:
put(key,value);
get(key);
remove(key);
5. Enumeration
● Used to traverse elements.
● Predecessor of Iterator.
Methods:
hasMoreElements();
nextElement();
Java Program Using Vector (Legacy Class)
import [Link];
class Main {
public static void main(String[] args) {
Vector<String> v = new Vector<>();
[Link]("Java");
[Link]("Python");
[Link]("C++");
[Link](v);
Output
[Java, Python, C++]
9) Explain how Priority Queue class is created and
performs various operations on Priority Queue class.
Definition
The PriorityQueue class is a part of Java Collections Framework that implements the Queue
interface and provides the functionality of a heap data structure. Elements are retrieved
according to their priority rather than insertion order. By default, the smallest element has the
highest priority.
Creation of PriorityQueue
import [Link];
PriorityQueue<Integer> pq = new PriorityQueue<>();
This creates a priority queue where elements are processed in ascending order.
Operations on PriorityQueue
1. add()
Inserts an element into the queue.
[Link](4);
2. offer()
Inserts an element into the queue.
[Link](2);
3. peek()
Returns the head element without removing it.
[Link]();
4. poll()
Returns and removes the head element.
[Link]();
5. remove()
Removes a specified element.
[Link](2);
6. iterator()
Used to traverse elements of the queue.
Iterator<Integer> itr = [Link]();
Example Program
import [Link];
class Main {
public static void main(String[] args) {
PriorityQueue<Integer> pq = new PriorityQueue<>();
[Link](4);
[Link](2);
[Link](1);
[Link]("PriorityQueue: " + pq);
[Link]("Head Element: " + [Link]());
[Link]("Removed Element: " + [Link]());
[Link]("Updated Queue: " + pq);
}
}
Output
PriorityQueue: [1, 4, 2]
Head Element: 1
Removed Element: 1
Updated Queue: [2, 4]
Advantages of PriorityQueue
1. Automatically maintains priority order.
2. Efficient insertion and deletion.
3. Implements Queue interface.
4. Useful in scheduling, task management, and graph algorithms.
10) Explain how ArrayDeque class is created and
performs various operations on ArrayDeque class.
Definition
The ArrayDeque class is a part of Java Collections Framework that implements both the
Queue and Deque interfaces. It allows insertion and deletion of elements from both ends and
uses arrays internally.
Creating an ArrayDeque
import [Link];
ArrayDeque<String> animals = new ArrayDeque<>();
This creates an ArrayDeque capable of storing String objects.
Operations on ArrayDeque
1. add()
Adds an element at the rear.
[Link]("Dog");
2. addFirst()
Adds an element at the beginning.
[Link]("Cat");
3. addLast()
Adds an element at the end.
[Link]("Horse");
4. offer()
Inserts an element at the rear.
[Link]("Dog");
5. offerFirst()
Inserts an element at the beginning.
[Link]("Cat");
6. offerLast()
Inserts an element at the end.
[Link]("Horse");
7. getFirst()
Returns the first element.
[Link]();
8. getLast()
Returns the last element.
[Link]();
Example Program
import [Link];
class Main {
public static void main(String[] args) {
ArrayDeque<String> animals = new ArrayDeque<>();
[Link]("Dog");
[Link]("Cat");
[Link]("Horse");
[Link]("ArrayDeque: " + animals);
[Link]("First Element: "
+ [Link]());
[Link]("Last Element: "
+ [Link]());
}
}
Output
ArrayDeque: [Cat, Dog, Horse]
First Element: Cat
Last Element: Horse
Advantages of ArrayDeque
1. Faster than Stack for stack operations.
2. Can work as both Queue and Stack.
3. Supports insertion and deletion from both ends.
4. Efficient implementation using arrays.
Explain the methods defined by the following interfaces:
i) Collection Interface
The Collection interface is the root interface of Java Collections Framework and provides basic
operations for collections.
Method Description
add() Adds an element
remove() Removes an element
size() Returns number of elements
isEmpty() Checks whether collection is empty
contains() Searches for an element
Examples
[Link]("Java");
[Link]("Java");
[Link]();
[Link]();
[Link]("Java");
ii) List Interface
The List interface represents an ordered collection that allows duplicate elements and
index-based access.
Method Description
add() Adds an element
get() Retrieves element by index
set() Modifies element
remove() Removes element
indexOf() Returns index of element
Examples
[Link]("Java");
[Link](0);
[Link](1,"Python");
[Link](0);
[Link]("Java");
iii) NavigableSet Interface
NavigableSet extends SortedSet and provides methods for navigating sorted elements. It is
implemented by TreeSet.
Method Description
first() Returns smallest element
last() Returns largest element
higher() Returns next greater element
lower() Returns next smaller element
ceiling() Returns equal or next greater element
floor() Returns equal or next smaller element
Examples
[Link]();
[Link]();
[Link](4);
[Link](4);
[Link](4);
[Link](4);
iv) Queue Interface
The Queue interface stores and accesses elements in FIFO order.
Method Description
add() Inserts element
offer() Inserts element
peek() Returns front element
poll() Removes and returns front element
remove() Removes element
Examples
[Link](10);
[Link](20);
[Link]();
[Link]();
[Link]();
Define a Comparator. Mention the methods provided by
the Comparator interface. Illustrate its use with a program
that demonstrates sorting elements in a TreeSet in
reverse order.
Definition
The Comparator interface belongs to the [Link] package and is used to define a custom
ordering of objects. It allows sorting elements according to user-defined criteria instead of the
default natural ordering.
Methods of Comparator Interface
1. compare()
Compares two objects and returns an integer value.
int compare(T o1, T o2);
Return values:
● Negative → first object comes before second
● Zero → objects are equal
● Positive → second object comes before first
2. equals()
Checks whether two comparator objects are equal.
boolean equals(Object obj);
Program to Sort TreeSet in Reverse Order
import [Link];
import [Link];
class ReverseComparator implements Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
return [Link](a);
}
}
public class Main
{
public static void main(String[] args)
{
TreeSet<Integer> set =
new TreeSet<>(new ReverseComparator());
[Link](10);
[Link](40);
[Link](20);
[Link](30);
[Link](set);
}
}
Output
[40, 30, 20, 10]
Working
1. A class ReverseComparator implements the Comparator interface.
2. The compare() method is overridden.
3. [Link](a) reverses the natural order.
4. TreeSet uses this comparator while inserting elements.
5. Elements are stored and displayed in descending order.
Discuss the various methods provided by
the Arrays class in Java. Illustrate the
usage of these methods with a suitable
example program.
Arrays Class
The Arrays class belongs to the [Link] package and provides various utility methods for
performing operations on arrays. These methods help in sorting, searching, comparing, filling,
and displaying array elements efficiently.
Methods of Arrays Class
1. sort()
Used to sort array elements in ascending order.
[Link](arr);
2. binarySearch()
Used to search an element in a sorted array and returns its index.
[Link](arr,30);
3. fill()
Used to fill all elements of an array with a specified value.
[Link](arr,5);
4. equals()
Used to compare two arrays and returns true if both arrays contain identical elements.
[Link](arr1,arr2);
5. toString()
Used to convert an array into a string representation.
[Link](arr);
Example Program
import [Link];
public class Main
public static void main(String[] args)
int arr[] = {40, 10, 30, 20};
[Link]("Original Array : "
+ [Link](arr));
[Link](arr);
[Link]("After Sorting : "
+ [Link](arr));
int pos = [Link](arr, 30);
[Link]("Position of 30 : "
+ pos);
[Link](arr, 5);
[Link]("After Fill : "
+ [Link](arr));
int arr2[] = {5, 5, 5, 5};
[Link]("Arrays Equal : "
+ [Link](arr, arr2));
Output
Original Array : [40, 10, 30, 20]
After Sorting : [10, 20, 30, 40]
Position of 30 : 2
After Fill : [5, 5, 5, 5]
Arrays Equal : true