Java Collections
Framework
Streamlining Data Structures in Java
Collection Framework
Any group of individual objects that are represent as a single unit
is known as a Java Collection of Objects.
In Java, a separate framework named the "Collection
Framework" has been defined in JDK 1.2 which holds all the Java
Collection classes and interfaces in it.
In Java, Collection Interface (java.util.Collection) and Map
Interface (java.util.Map) are two main "root" interfaces of Java
Collection classes.
What is a Framework?
A Framework in a programming is a predefined set of tools,
libraries, and rules designed to simplify software development.
It provides the foundation or template that developers can build
upon, allowing them to focus on the logic of their application.
In simple terms, It is like a skeleton or blueprint for building an
application.
Need of Collection Framework?
Before the Collection Framework, the standard methods for grouping
java objects were Arrays, Vectors or Hashtables.
All these collections had no common interface, through the main aim
of these collections is same.
Implementation of all these collections was defined independently.
It is very difficult for developers to remember all different methods,
syntax, and constructors present in every collection class.
Example Java Code Snippets
without Collection Framework
Most of the Vector methods are final, meaning we cannot extend
the vector class to implement a similar kind of collection.
Advantages of Collection
Framework
Consistent API
o The API has a basic set of interfaces like Collection, List, Set or Map, all the
classes that implement these interfaces have some common set of methods.
Reduces programming effort
o A Programmer doesn't have to worry about the design of the Collection but
rather he can focus on its best use in his program.
Increases program speed and quality
o Programmer no need to think of the best implementation of specific data
structure. Instead, he can simply use it to boost the performance of program.
Hierarchy
of
Collection
Framework
Iterable Interface
Traversing Collections one by one
Iterable Interface
It is part of the Java Collections Framework and represents a
collection of objects that can be iterated one by one.
Purpose:
o To provide common way to traverse collections (e.g., lists, queue, sets.).
o Enables enhanced for-loops (for-each loop) in java.
Package: Located in Java.lang package.
Implemented By:
o All collection classes in java (e.g., ArrayList, LinkedList, HashSet etc.,)
Methods:
o iterator(): Returns an iterator object to traverse the collection.
How Iterable Works?
For-each Loop Iterator
Advantages of Iterable
Provides a uniform way to traverse collections.
Supports enhanced for-loops, making code concise and readable.
Enables custom iteration logic using Iterator.
Limitations of Iterable
Only Provides forward traversal through the collection.
For bidirectional traversal, you need ListIterator.
Collection Interface
Root Interface of Java Collection Hierarchy
Collection Interface
The collection interface is a core member of Java
Collections Framework.
It is located in java.util package.
It is not directly implemented by any class.
Instead, it is implemented indirectly through its sub-interfaces
like list, queue, set.
Map is not part of collection hierarchy but belongs to the Java
Collection Framework.
Basic Methods of Collection
Interface
Method Return Type Description
add(E e) boolean Adds an element to the collection
remove(Object o) boolean Removes a specific element from the
collection
size() int Returns the number of elements in the
collection
isEmpty() boolean Checks if the collection is empty.
contains(Object o) boolean Checks if the collection contains the specific
element
iterator() iterator Returns the iterator over the elements from
the collection
toArray() Object[] Converts the collection to an array
toArray(T[] a) T[] Converts the collection to an array of the
specific type
Bulk Operations of Collection
Interface
boolean addAll(Collection<? extends E> c)
o Adds all elements from another collection to this collection.
boolean removeAll(Collection<?> c)
o Removes all elements from this collection that are present in another
collection.
boolean retainsAll(Collection<?> c)
o Retains only the elements in this collection that are present in another
collection.
void clear()
o Removes all elements from the collection.
Advantages of Collection Interface
Uniformity
o Provides a common set of methods for all collections.
Flexibility
o Enables switching between different implementations (e.g., ArrayList,
LinkedList)
Reusability
o Encourage reusable and maintainable code.
Limitations of Collections
Interface
Does not include methods for random access (Specific to List).
Cannot handle Key-Value mappings (Map is separate).
List Interface
Ordered collection of elements
List Interface
The List Interface is a sub interface of the Collection
interface in java.
It represents an ordered collection of elements that allows
duplicate and provides index-based access to elements.
So in Java List, you can organize and manage the data
sequentially.
Key Features of List Interface
Ordered Collection
o Maintains the insertion order of elements.
Allows Duplicates
o A List can have multiple occurrences of the same element.
Index-based access
o Elements can be accessed, added, or removed using their index.
Sub-interface of Collection
o Inherits the methods from the Collection Interface.
Implementations of List Interface
ArrayList
o Dynamic array implementation.
o Faster for accessing elements.
LinkedList
o Doubly linked list implementation.
o Efficient for frequent insertion and deletion operations.
Vector
o Synchronized version of ArrayList.
Stack
o Extends Vector to provide a Last-In-First-Out (LIFO) implementation.
Index-based Methods of List
Interface
Method Return Type Description
add(int index, E void Inserts an element at the specified
element) position
get(int index) E (element) Returns the element at the specified
position
remove(int index) E (element) Removes the element at the specified
position
indexOf(Object o) int Returns the first occurrence index of the
specified element
lastIndexOf(Object o) int Returns the last occurrence index of the
specified element
Bulk Operations of List Interface
boolean addAll(int index, Collection<? extends E> c)
o Insert all elements at the specified position.
ListIterator<E> listIterator()
o Returns a ListIterator for the list.
ListIterator<E> listIterator(int index)
o Returns a ListIterator starting at the specified position.
Advantages of List Interface
Dynamic Nature
o Can grow or shrink dynamically (in implementations like ArrayList and
LinkedList)
Flexibility
o Provides multiple ways to access, modify, and iterate over elements.
Order Maintenance
o Preserves the insertion order.
Limitations of List Interface
Thread Safety
o Not Synchronized (expect Vector)
o Use Collections.synchronizedList() for thread-safe operations.
Performance Trade-offs
o Random access in LinkedList is slower compared to ArrayList.
ArrayList
Dynamic Arrays
ArrayList
The ArrayList class in Java is a part of the Java Collections
Framework.
It is resizable array implementation of the List Interface, which
means it can grow and shrink dynamically as elements are
added or removed.
SYNTAX:
Key features of ArrayList
Dynamic Resizing
Order Preservation
Allows Duplicates
Index-Based Access
Not Synchronized
Creating an empty ArrayList
Integer ArrayList
Class Name Generic Type variable name Class Constructor
Generics
Generics in java provides a way to create a type-safe
collections.
This helps you prevent type-safe related errors at compile
time and promotes code reusability.
Generics are primarly used in List, Set and Map, but can
also be applied to Classes, interfaces and methods.
The Syntax of generics involves using angle brackets '<>' to
enclose the type parameter.
Generics
CRUD Operations on ArrayList
Inserting Elements Updating Elements
Reading elements by index
Deleting Elements
Inserting Elements in ArrayList
Insertion of 3 Integer Values
20 500 99
0 1 2
Inserting 40 Integer value at index position 2
20 500 40 99
0 1 2 3
Removing Elements in ArrayList
20 500 40 99
0 1 2 3
Removing Integer element at index position 1
20 40 99
0 1 2
Code
snippet of
ArrayList
Advantages of ArrayList
Dynamic Size
o Grows or Shrinks automatically.
Index-based Access
o Provides fast random access to elements o(1) complexity.
Rich API
o Offers many utility methods for manipulating elements
Limitations of ArrayList
Slow Insertion and Deletion
o If elements need to be shifted, these operations take o(n) time.
Not Thread-Safe
o Requires external Synchronization for multi-threaded application.
Memory Overhead
o Consumes more memory than array due to dynamic resizing.
LinkedList
Doubly Linked List Implementation
LinkedList
LinkedList is part of Java Collections Framework.
It is a doubly linked list implementation.
It allows efficient insertion and deletion of elements.
Best suited for use-cases where these operations are frequent.
SYNTAX:
Key Features of LinkedList
Doubly Linked List
Implements List and Deque interfaces
Dynamic Size
Allows Duplicates
Maintains Insertion Order
Doubly Linked List
Doubly Linked List
In Doubly Linked List, each node contains:
o The data (value)
o A reference (pointer) to the previous node
o A reference (pointer) to the next node
To access an element, the LinkedList must traverse the list
node by node, starting from the head (or tail if closer), until it
reaches the desired index.
Why LinkedList can't randomly access like
ArrayList using index-based approach?
Unlike an ArrayList, a LinkedList does not have an underlying array or
contiguous memory for its elements.
In ArrayList, accessing an element at a specific Index is constant-time
operation O(1) because the index is directly mapped to the memory location.
In LinkedList, elements are scattered across memory locations because each
node is dynamically allocated.
This makes it harder for the CPU to leverage cache locality, which speeds up
sequential data access in arrays (ArrayList benefits from this).
Creating an empty LinkedList
Class Name Generic Type variable name Class Constructor
Inserting Elements in LinkedList
Inserting an String element at Index Position 1
HEAD TAIL
Prev
Next
Next
Prev
Next
Prev
Grapes Banana Mango
Next
Null
Prev
Null Apple
Accessing Elements in LinkedList
Accessing an element by using Index Postion 2
HEAD TAIL
Prev
Next
Next
Prev
Next
Prev
Grapes Banana Mango
Null
Null
Code
snippet of
ArrayList
and
LinkedList
Advantages of LinkedList
Efficient Insertions and Deletions
o Adding/Removing elements at the head, tail, or middle is faster compared
to an ArrayList
Implementation Deque
o Can be used as a queue, deque, or stack.
Dynamic Resizing
o No need to specify an initial capacity.
Limitations of LinkedList
Slow random access
o Accessing elements by index takes O(n) time.
Memory Overhead
o Requires external memory for storing node pointers.
Poor cache performance
o Due to non-contiguous memory allocation.
Q&A
Theoretical Questions
What is the Collections Framework in Java ?
What is difference between Iterable and Collection Interfaces in Java?
List three key differences between ArrayList and LinkedList?
What is the purpose of the List Interface in the Collection Framework?
How does the ArrayList handle dynamic resizing, and how does it
differ from a regular array?
Scenario based Questions
You have a list of numbers. Write a Java snippet to find if a
specific number (e.g., 55) exists in an ArrayList.
You have an ArrayList of integers that may contain duplicates.
Write a program to remove all duplicates.
You have a LinkedList of Student objects, where each student
has a name and score. Write a snippet to:
o Sort the students by score in descending order.
o Sort by name alphabetically.
Scenario based Questions
You have ArrayList of Employee objects with id, name and
salary attributes. Write a Java Code snippet to:
o Update the salary of the employee based on the given id.
o Delete the employee details from the list based on given id.
Ø You have a LinkedList of Integers. Write a Program to:
o Reverse the list in-place without using another data structure.
o Iterate over the reversed list and print the elements.
Class Relationships
Understanding Class Interactions
Class Relationships
Class relationships in Java describe how classes interact with
each other in Object-Oriented Programming.
These relationships helps in designing reusable,
maintainable, and modular code.
Types of Class Relationships
There are five types of relationships in Java.
1. Association
One Class is associated with another Class.
2. Aggregation
A "Whole-part" relationship, where the part can exist independently of the
whole.
3. Composition
§ A "Whole-part" relationship, where the part cannot exist independently of the
whole.
4. Inheritance
§ One class derives from another Class (IS-A Relationship)
5. Dependency
§ One class depends on another class to function (Uses-A Relationship)
Association
Association represents a uses-A relationship between two
classes.
The objects involved in association are independent of each
other and can exists on their own.
Weak Relationship.
Example relationships in real-world are Person -> Bank
Account.
Aggregation
Aggregation is a specialized form of Association where one
class is a collection or container of other classes.
Those contained classes can still exists independently.
In other words, one class has a reference to another class, but
the contained objects have their own life cycle.
Example relationships in real-world are Library -> Books.
Composition
Composition is a strong form of aggregation where one class
owns another class, and the owned class cannot exists
independently.
If the owning object is destroyed, then the composed object is
also destroyed.
Example relationships in real-world are Human -> Heart.
Inheritance
Inheritance is a relationship where one class (sub class)
can inherits the fields and methods of the another class
(super class).
This is also known as IS-A relationship because the
subclass is a type of the super class.
Example relationships in real-world are Animal -> Cat.
Dependency
• Dependency is a uses-a relationship where one class
depends on another class to perform its functions.
• This is a weaker relationship when compared to association
and often involves passing objects as parameters to
methods.
• Example relationships in real-world are Computer ->
Printer.
Thank you