Java Collection Framework Overview
Java Collection Framework Overview
1
Motivation (Problem with arrays)
• Arrays:
➢ Arrays in Java are fundamental data structures used to store multiple values of the same
data type in a single variable.
➢ But are they flexible enough? (e.g. Can we change size?)
2
Motivation (Problem with arrays)
Problem Explanation Example
Once an array is created, its size cannot
int[] nums = new int[3]; → we can’t
Fixed Size be changed. We must know the size in a
add a 4th element.
dvance.
No built-in way to add, remove, or search
elements efficiently. Only a few methods To remove an element, we need to
Lack of Built-in Methods
in Arrays class. Mostly, we must write manually shift elements.
our own logic.
Cannot Store Heterogeneous Arrays can only store one type of data
String[] names can’t store an Integer.
Objects (primitive or object).
If we create a large array but do not use int[] data = new int[1000]; but we
Poor Memory Efficiency
it, the unused elements waste memory. only use 10 elements. (waste)
3
Motivation (Problem with arrays)
• Why Collection Framework?
To solve these problems, Java introduced the Collection Framework, a set of ready-made
data structures that are:
Formal Definition:
• A collection is an object that represents a group of objects.
• A collections framework is a unified architecture for representing and manipulating
collections, enabling collections to be manipulated independently of implementation details.
4
Motivation (Problem with arrays)
• Primary advantages of using a framework?
✓ Reduces programming effort by providing data structures and algorithms so we don't have
to write them yourself.
✓ Increases performance by providing high-performance implementations of data structures
and algorithms. Because the various implementations of each interface are interchangeable,
programs can be tuned by switching implementations.
✓ Provides interoperability between unrelated APIs by establishing a common language to
pass collections back and forth.
✓ Reduces the effort required to learn APIs by requiring you to learn multiple ad hoc
collection APIs.
✓ Reduces the effort required to design and implement APIs by not requiring you to produce
ad hoc collections APIs.
✓ Fosters software reuse by providing a standard interface for collections and algorithms with
which to manipulate them.
[Link]
[Link]#:~:text=The%20Java%20platform%20includes%20a,with%20which%20to%20manipulate%20them.
5
Motivation (Using ArrayList instead of Array)
import [Link];
Output:
Names: [Alice, Bob, Charlie, David]
After removal: [Alice, Charlie, David]
6
Motivation
!! Do not confuse with Arrays (data structure), Arrays Utility Class and ArrayList<> !!
1. Arrays:
An array itself in Java is a low-level fixed-size container —
it’s part of the language, not part of the Collections Framework.
nums[1] = 5;
[Link]([Link]); // ok
// But we can’t do [Link](4);
import [Link];
public class Example {
public static void main(String[] args) {
int[] nums = {3, 1, 2};
3. The ArrayList<>:
[Link] is a helper class that provides static utility methods to work with arrays.
import [Link];
import [Link];
public class Example {
public static void main(String[] args) {
10
Motivation
Food for thought!!
11
Overview of the Java Collection Framework
• Java collection framework is not all just about ArrayList.
• It has more interfaces, implementations, and algorithms.
[Link] 12
Overview of the Java Collection Framework
public interface Collection<E> extends Iterable<E> E - the type of elements in this list
14
Java List Interface
Most commonly used list methods
Method Description
add() Adds an element to the end of the list public interface List<E>
get() extends Collection<E> {
Returns the element at the specified position
boolean add(E e);
set() Replaces the element at the specified position E get(int index);
E remove(int index);
remove() Removes the element at the specified position int size();
size() Returns the number of elements in the list // ... many more
}
✓ Any class that implements me must provide its own way to add,
For more details:
remove, and get elements [Link]
4/docs/api/[Link]/java/util/[Link]
15
Java ArrayList<>
• An ArrayList in Java is a resizable (or dynamic) array from the [Link] package that can grow or
shrink automatically as elements are added or removed, unlike regular arrays with a fixed size.
16
Java ArrayList<>
ArrayList Constructors
1. ArrayList()
3. ArrayList(int initialCapacity)
This constructor is used to build an array list with the initial capacity being specified.
17
Java ArrayList<>
import [Link].*;
class Example{
Entire Output:
19
Java ArrayList<> (Memory Allocation)
[Link] 20
Questions
1. Which of the following statements about the Java Collection Framework is true?
A. Iterable
B. Collection
C. List
D. Set
21
Questions
4. Guess the output:
import [Link].*;
public class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
[Link]("A");
[Link]("B");
[Link](1, "C");
[Link](names);
}
}
5. What happens if you try to access an element at an invalid index in an ArrayList (e.g., index =
10 when size = 5)?
A. Returns null
B. Returns -1
C. Throws IndexOutOfBoundsException
D. Silently ignores the call
22
Wrapper Class (its use in Collections)
• Motivations :
✓ Java collections framework works on OBJECTS! Not on primitive datatypes.
✓ ArrayList<int> list = new ArrayList<int>();//Invalid
✓ int is a primitive datatype NOT an object.
✓ Similarly, we also need utility methods like parsing and comparisons.
✓ Consistency with object-oriented programming concept.
• Definition:
✓ A wrapper class is a class that encloses or ‘wraps’ primitive data type into an object.
✓ Each primitive data type has a wrapper class.
✓ Collections like ArrayList work with the wrapper class object rather than the primitive type.
Primitive
Wrapper Class ArrayList<Integer> numbers = new ArrayList<Integer>();
Type
[Link](10);
byte Byte [Link](20);
short Short
Similarly,
int Integer
ArrayList<Double> list = new ArrayList<Double>();
long Long
float Float ArrayList<Float> list = new ArrayList<Float>();
double Double
LinkedList<Double> prices = new LinkedList<>();
char Character [Link](19.99); // double → Double
boolean Boolean [Link](5.75);
25
Wrapper Class (its use in Collections)
• Utility Methods :
1. Parsing(Example):
✓ Method→[Link](String s)
✓ Converts a numeric string into an int value.
Usefulness: When we get numbers as user input (String) e.g., from Scanner or GUI
we can convert them to numeric types for calculations.
26
Wrapper Class (its use in Collections)
• Utility Methods :
double pi = 3.14;
String s = [Link](pi);
[Link](s + " is Pi");// Output: 3.14 is Pi)
Usefulness: When you need to display or store numbers as text (e.g., file or message)
27
Wrapper Class (its use in Collections)
• Autoboxing and Unboxing :
✓ Java provides automatic conversion between primitive type and their
corresponding wrapper objects.
int x = 5;
Integer y = x; // autoboxing → [Link](x)
28
Wrapper Class (its use in Collections)
• Unboxing (Primitive to Object):
✓ Unboxing is the automatic conversion a wrapper class object to its
corresponding primitive type.
✓ This conversion occurs when a wrapper object is used in a context that expects
a primitive value, such as:
• Assigning a wrapper object to a variable of its corresponding primitive type.
29
Wrapper Class (its use in Collections)
Autoboxing
Unboxing
30
Wrapper Class (its use in Collections)
import [Link]; Take input: Scores of 5 mental coding tests
import [Link];
[Link]();
}
}
33
ArrayList<> of Custom objects
Motivation (Why we need to store objects?)
✓ Example:
✓ But, what if we want to add both name and student ID/Roll Number?
✓ Then, we need to introduce a custom class Student.
34
ArrayList<> of Custom objects
Step-1: Define a simple class
class Student {
String name;
int roll;
35
ArrayList<> of Custom objects
Step-2: Create ArrayList<Student> and add objects
import [Link].*;
36
ArrayList<> of Custom objects
We may add more functionalities like search and access object fields
[Link](1).name = "Bobby";
[Link]("Updated: " + [Link](1));
37
ArrayList<> of Custom objects
What to do if Student attributes are Private?
• Add Getter/Setter Methods: • Access through those methods
class Student { for (Student s : students) {
private String name; [Link]("Name: "
private int roll; + [Link]());
}
public Student(String name, int roll) {
[Link] = name;
[Link] = roll;
}
Why we made custom search functionality when ArrayList already has in-built search method?
[Link]([Link](”Alice")); // true
[Link]([Link](”Kim")); // 1
39
ArrayList<> of Custom objects
How about with custom objects?
class Student {
String name; • It uses the default implementation from
int id; Object, which compares memory addresses,
Student(String name, int id) { not field values.
[Link] = name; • So two different Student objects with the same
[Link] = id; data are considered not equal.
}
}
40
Questions
• Which of the following statements about ArrayList is true?
A. It has a fixed size once created.
B. It allows duplicate elements.
C. It cannot store null values.
D. It only stores primitive data types.
41
Questions
• What will the following print?
Integer x = [Link]("25");
[Link](x * 2);
42
Java LinkedList<>
• Motivations :
✓ ArrayList is backed by a contiguous array, inserting or removing
elements in the middle requires shifting all subsequent elements.
43
Java LinkedList<>
• LinkedList (on the contrary) :
✓ internally maintains nodes connected by references (next and prev).
So, inserting or deleting in the middle just updates a few pointers -- no
shifting required!
LinkedList<String> list = new LinkedList<>(); • Works fine!
[Link]("A"); • internally:
[Link]("B"); o "C" is added by just
[Link]("D"); adjusting node references.
o No element shifting.
// Insert element in the middle
[Link](2, "C"); // Insert at index 2
[Link](list);
Each node in a linked list:
Reference to Data Reference to
previous the next node
node
44
Java LinkedList<>
Insertion in a LinkedList
(Internal Process)
[Link]
Java LinkedList<>
Deletion in a LinkedList
(Internal Process)
[Link]
Java LinkedList<>
List of features
Aspect Description
Implemented as a doubly linked list — each node has references to the
Implementation Type
previous and next nodes.
Found in [Link] package. Implements List, Deque, Queue, Cloneable,
Package & Interfaces
and Serializable interfaces.
Maintains insertion order of elements — elements are stored in the
Ordering
sequence they were added.
Duplicates Allows duplicate elements just like ArrayList.
Null Elements Can store null values.
Automatically grows or shrinks as elements are added or removed
Dynamic Size
(no fixed size).
47
Java LinkedList<>
List of features (Contd.)
Aspect Description
Slower random access (O(n)) since it must traverse nodes sequentially
Access Time
to reach an index.
Faster insertion and deletion (especially in the middle or ends) — no
Insertion/Deletion
shifting of elements like in ArrayList.
Traversal Can be traversed in both directions using an iterator (ListIterator).
Requires more memory than an ArrayList because each element stores
Memory Overhead
two extra references (to previous and next nodes).
Ideal for scenarios where frequent insertion/deletion occurs — e.g., q
Use Cases
ueues, stacks, playlists, undo/redo systems.
Slower random access (O(n)) since it must traverse nodes sequentially
Access Time
to reach an index.
48
Java LinkedList<> (Example of usage)
import [Link];
50
Java LinkedList<> (Comparison)
Choose ArrayList when:
• Frequent insertions or deletions are performed, especially at the beginning, end, or in the middle
of the list.
• Random access by index is not a primary operation.
51
Overview of the Java Collection Framework (Revisit)
[Link] 52
Java Queue Interface
• The Queue interface is part of the Java Collections Framework and belongs to [Link] package.
• We cannot access elements by their index
• We can add duplicates.
• Elements are processed in the order determined by the queue implementation (First In First Out or
FIFO for LinkedList, priority order for PriorityQueue).
• Since Queue is an interface, we cannot create a Queue object directly.
• Instead, we use a class that implements the Queue interface, such as:
✓ LinkedList
✓ PriorityQueue Isn’t
LinkedList a
✓ ArrayDeque
List?
53
Java Queue Interface (Simplified Hierarchy)
54
Java Queue Interface
• Working of Queue Data Structure:
✓ Elements are stored and accessed in First In, First Out manner.
✓ That is, elements are added from the behind and removed from the front.
Deque 55
Java Queue Interface
Most commonly used Queue methods
Returns special
Method Description Throws Exception?
value (null/false)?
Yes (if capacity is full —
boolean add(E e) Inserts the element into the queue. No
in bounded queues).
Inserts element, returns false if
boolean offer(E e) queue is full (preferred for capacity- No Yes (false if full)
restricted queues).
Removes and returns the head (front)
E remove() Yes (if queue is empty). No
of the queue.
Removes and returns the head of the
E poll() No Yes (null if empty)
queue.
Returns (but does not remove) the
E element() Yes (if queue is empty). No
head of the queue.
Returns (but does not remove) the
E peek() No Yes (null if empty)
head of the queue.
56
Java Deque Interface
58
Java Queue Interface (Example: Implemented by LinkedList)
// Remove elements
[Link]("Removed (remove): " + [Link]()); // Removes A
[Link]("Removed (poll): " + [Link]()); // Removes B
[Link]("After removals: " + q);
Complete Output:
59
Java Deque Interface (Example: Implemented by LinkedList)
import [Link];
import [Link];
60
Java Deque Interface (Example: Implemented by
LinkedList)
// Peek elements
[Link]("Front element (peekFirst): " + [Link]());
[Link]("Rear element (peekLast): " + [Link]());
62
Java Queue Interface (Implemented by Class PriorityQueue)
• A PriorityQueue in Java is a queue where elements are ordered based on their priority, rather
than the order of insertion.
• By default, it uses natural ordering (min-heap), but a custom comparator can be used to define
different priorities.
• Uses a heap data structure internally to ensure efficient insertion and removal of the highest-
priority element.
63
Java Queue Interface (Implemented by Class PriorityQueue)
import [Link];
65
Java Queue Interface (Implemented by Class PriorityQueue)
66
Overview of the Java Collection Framework (Revisit)
[Link] 67
Java Set Interface
• The Set interface in Java is part of the Collections Framework and represents a collection of unique
elements.
• Implemented by the following classes:
Implementation Special Feature
HashSet Fastest, no order maintained.
LinkedHashSet Maintains insertion order.
TreeSet Automatically sorted (natural or custom comparator).
• Main Features
Feature Explanation
No duplicates allowed A Set automatically ignores duplicate elements.
Unordered collection Elements do not maintain insertion order (except LinkedHashSet).
Can contain null Most Set implementations allow null (HashSet allows one null).
Fast operations Hash-based sets offer near-constant time for add, remove, contains.
68
Java Set Interface
• Common Methods
Method Description Example
Adds an element if it is not already
boolean add(E e) [Link](10);
present. Returns true if added.
Removes an element if present. Returns
boolean remove(Object o) [Link](10);
true if removed.
boolean contains(Object o) Checks if an element exists in the set. [Link]("A");
Returns the number of elements in the
int size() [Link]();
set.
boolean isEmpty() Checks if the set is empty. [Link]();
void clear() Removes all elements from the set. [Link]();
69
Java Set Interface (Class HashSet)
import [Link];
// Adding elements
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("Alice"); // duplicate → ignored
70
Java Set Interface (Class HashSet)
// Removing element
[Link]("Charlie");
71
Java Set Interface (Class HashSet)
❖ When to use HashSet?
• When we want to avoid duplicates
• When ordering is not important
• When speed is required (fast lookup)
72
Questions
1. Which of the following allows duplicate elements?
(a) ArrayList
(b) LinkedList
(c) HashSet
(d) Both (a) and (b)
3. True or False:
A LinkedList can be used as both a List and a Queue.
73
Questions
74