Collection Framework
Collection Framework
✓ [Link]
SortedMap
Set List
SortedSet
Application of Major Components
REDUCES
DYNAMIC DATA UNIFIED INCREASES
PROGRAMMING
SIZING INTEGRITY ARCHITECTURE PROGRAM SPEED
EFFORT
AND QUALITY
Constructor Description
ArrayList() build an empty array list.
ArrayList(Collection c) build an array list with the elements of the collection.
ArrayList(int capacity) build an array list that has the specified initial capacity.
Characteristics of ArrayList
✓ Resizable: ArrayList automatically grows as elements are added. There is no fixed size,
unlike arrays.
✓ Ordered: Elements in an ArrayList are stored in the order in which they are inserted. It
maintains the insertion order.
✓ Index-based Access: Elements can be accessed via indices (positions in the list),
similar to arrays.
✓ Allows Duplicate Elements: ArrayList allows duplicate elements.
✓ Allows Null Values: You can store null values in an ArrayList.
✓ Not Synchronized: ArrayList is not synchronized, if multiple threads access it
simultaneously.
Methods of ArrayList
Method Description
add(E e) Adds an element to the end of the list.
add(int index, E element) Inserts an element at a specific index.
get(int index) Retrieves the element at the specified index.
remove(int index) Removes the element at the specified index.
size() Returns the number of elements in the list.
isEmpty() Checks if the list is empty.
contains(Object o) Checks if the list contains the specified element.
clear() Removes all elements from the list.
set(int index, E element) Replaces the element at the specified index with a new element.
indexOf(Object o) Returns the index of the first occurrence of the specified element.
boolean addAll(Collection c) Appends all of the elements from the collection to the end of this
list
Iterate an ArrayList
for-each loop
for(Object fruit: list){
ArrayList list = new ArrayList(); [Link]((String)fruit+" ");
}
[Link]("Apple");
[Link]("Banana");
forEach Method (Java 8+)
[Link]("Orange");
[Link]("Mango");
[Link](fruit -> [Link](fruit));
Iterator ([Link])
for loop Iterator iterator = [Link]();
for (int i = 0; i < [Link](); i++) { while ([Link]()) {
[Link]([Link](i)); [Link]([Link]());
} }
ArrayList Example // Removing element from ArrayList
// Remove Orange
Iterator itr = [Link]();
while([Link]()){
import [Link]; String fruit = (String) [Link]();
if([Link]("Orange")){
public class ArrayListExample { [Link]();
public static void main(String[] args) { }
}
// Creating an ArrayList [Link]("ArrayList after remove:");
ArrayList list = new ArrayList(); for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
// Adding elements to the ArrayList }
[Link]("Apple");
[Link]("Banana"); }
[Link]("Orange"); } Note: The Iterator's remove() method is
[Link]("Mango"); designed to safely remove elements
// Displaying the ArrayList elements during iteration, while direct remove
[Link]("ArrayList elements:"); using remove(), can disrupt the iteration
for (int i = 0; i < [Link](); i++) { process and generate
[Link]([Link](i)); ConcurrentModificationException.
}
Sort ArrayList
public int compare(Object o1, Object o2): It is used to compare the current object with
the specified object. It returns -
• A negative integer if o1 should come before o2.
• A positive integer if o1 should come after o2.
• Zero if both are considered equal in terms of sorting order.
Sort ArrayList using Comparator
for(Student s: students){
[Link]();
}
}
}
Array vs ArrayList
Feature Array ArrayList
Fixed size. Once defined, cannot Dynamic size. Can grow or shrink as
Size be changed. needed.
Can store elements of only one Can store objects of any type
Type type (homogeneous). (heterogeneous), but typically used
with generics.
Memory is allocated at once. Memory is dynamically managed,
Memory increasing as needed.
Slightly faster for primitive types Slightly slower due to overhead
Performance due to direct memory allocation. (dynamic resizing, object storage,
etc.).
Storage Type Can store primitive types Can only store objects
Can contain null values only for Can store null values, even for
Null Values reference types. reference types.
Adding/Removing Cannot add or remove elements Supports adding, removing, and
Elements dynamically. modifying elements dynamically.
Generics
✓ Generics in Java are a mechanism that allows you to define classes, interfaces, and
methods with a placeholder for types.
✓ This provides stronger type checking at compile-time and allows code to be more
reusable and type-safe.
✓ The main idea behind generics is to provide a way to specify the types of objects a
class or method will work with, rather than using raw types.
✓ With generics, you specify the type of object the collection will hold (e.g.,
ArrayList<String> list = new ArrayList<>();) and the compiler ensures that only objects of
that type are added.
Generics
import [Link]; // Access elements without needing to cast
for (Integer number : numbers) {
public class GenericsExample { [Link](number);
public static void main(String[] args) {
}
// Create an ArrayList of Integer type using
Generics
// Compile-time error if you try to add
ArrayList<Integer> numbers = new a String to an ArrayList of Integers
ArrayList<>();
// [Link]("Hello"); // Error:
incompatible types
// Add some integers to the ArrayList }
[Link](10); }
[Link](20);
[Link](30);
Stack
Collection
Constructor Description
Stack() Constructs an empty stack.
Characteristics of Stack
✓ LIFO order: The most recently added element is the first one to be removed.
✓ Inheritance: Stack extends the Vector class, meaning it is backed by an array and
inherits methods for dynamic resizing.
✓ Thread Safety: It is synchronized, which means it is thread-safe for use in multi-
threaded applications. However, this comes with performance overhead.
✓ Legacy Class: Although the Stack class is part of the Java Collections Framework, it is
considered a legacy class. The Deque interface is recommended for stack
functionality in modern Java programs.
Methods of Stack
Constructor Description
LinkedList() Creates an empty LinkedList.
Creates a LinkedList containing the elements of the specified
LinkedList(Collection c)
collection.
Characteristics of LinkedList
✓ Doubly Linked List: Each element (node) has pointers to both the next and previous
elements.
✓ Dynamic Size: The size of a LinkedList can grow or shrink dynamically as elements are
added or removed.
✓ Ordered: LinkedList maintain the insertion order.
✓ Allows Duplicates: It allows duplicate elements.
✓ Null Elements: It allows null values.
✓ Slower Random Access: Since it doesn't allow direct access to elements (like an
array), accessing elements by index is slower compared to ArrayList. It needs to
traverse the list to reach a particular index.
✓ Efficient Insertions/Deletions: Inserting or deleting elements at the start or end of the list
is efficient because it doesn't require shifting elements like in an ArrayList.
Methods of LinkedList
Methods from List interface:
✓ add(E e): Adds an element at the end of the list.
✓ add(int index, E element): Inserts the specified element at the specified position in the
list.
✓ get(int index): Returns the element at the specified position.
✓ set(int index, E element): Replaces the element at the specified position with the
specified element.
✓ remove(int index): Removes the element at the specified position and return the
element.
✓ remove(Object o): Removes the specified object and return true/flase.
✓ size(): Returns the number of elements in the list
Methods of LinkedList
Methods from Deque interface (double-ended queue functionality):
✓ addFirst(E e): Adds the specified element at the front of the list.
✓ addLast(E e): Adds the specified element at the end of the list.
✓ removeFirst() / removeLast() : Removes and returns the first/last element. Throws
NoSuchElementException if queue is empty.
✓ pollFirst() / pollLast(): Removes and returns the first/last element. If the deque is empty, it
safely returns null instead of throwing an exception.
✓ peekFirst(): Retrieves the first element without removing it.
✓ peekLast(): Retrieves the last element without removing it.
Other Methods:
✓ clear(): Removes all elements from the list.
✓ contains(Object o): Returns true if the list contains the specified
LinkedList Example
import [Link]; // Access elements
[Link]("First Element: " +
public class LinkedListExample { [Link]());
public static void main(String[] args) { [Link]("Last Element: " +
// Create a LinkedList of String [Link]());
LinkedList<String> list = new LinkedList<>();
// Remove elements
// Add elements to the LinkedList [Link](); // Removes the first element
[Link]("Apple"); [Link](); // Removes the last element
[Link]("Banana");
[Link]("Cherry"); [Link]("After removing first and last
elements: " + list);
// Add elements at the beginning and the end
[Link]("Mango"); // Check if the list contains a specific element
[Link]("Grapes"); [Link]("Contains 'Banana'? " +
[Link]("Banana"));
// Iterate over the elements
[Link]("Iterating over elements:"); }
for (String fruit : list) { [Link](fruit); } }
ArrayList vs LinkedList
Feature ArrayList LinkedList
ordering).
Constructor Description
PriorityQueue() Creates a priority queue with natural ordering.
PriorityQueue(Comparator Creates a priority queue with the specified comparator
comparator)) that defines the ordering of the elements.
Characteristics of PriorityQueue
✓ add(E e): Inserts the specified element into the priority queue.
✓ peek(): Retrieves, but does not remove, the head of the queue (returns null if the
queue is empty).
✓ poll(): Retrieves and removes the head of the queue (returns null if the queue is
empty).
✓ remove(Object o): Removes a single instance of the specified element from the
queue, if present.
✓ size(): Returns the number of elements in the priority [Link](): Removes all
elements from the priority queue.
✓ contains(Object o): Checks if the queue contains the specified element.
PriorityQueue Example
import [Link]; // Remove and retrieve the head element
[Link]("Removed from the queue: " +
public class PriorityQueueExample { [Link]()); // Output: 10
public static void main(String[] args) {
// Create a priority queue with natural ordering // Display remaining elements
PriorityQueue<Integer> pq = new PriorityQueue<>(); [Link]("Remaining elements in the
queue: " + pq); // Output: [15, 20, 30]
// Add elements to the priority queue
[Link](10); // Check size of the queue
[Link](20); [Link]("Size of the queue: " +
[Link](15); [Link]()); // Output: 3
[Link](30); }
}
// Peek the head element (highest priority)
[Link]("Head of the queue: " + [Link]());
PriorityQueue with Custom Comparison
public class CustomCompare {
import [Link].*;
public static void main(String[] args) {
class Task{
TaskComparator taskComparator = new
String title;
TaskComparator();
int priority;
PriorityQueue<Task> tasks = new
Task(String title, int priority){
PriorityQueue<>(taskComparator);
[Link] = title;
[Link](new Task("Task 1", 10));
[Link] = priority;
[Link](new Task("Task 2", 5));
}
[Link](new Task("Task 3", 2));
void display(){
[Link](new Task("Task 4", 7));
[Link]([Link]+" "+[Link]);
[Link](new Task("Task 5", 5));
}
}
while ([Link]()>0) {
class TaskComparator implements Comparator<Task>{ Task t = [Link]();
@Override [Link]();
public int compare(Task t1, Task t2){ }
return [Link] - [Link]; } }
} }
HashMap
Map
✓ A HashMap in Java is part of the Java Collections Framework
and implements the Map interface.
AbstractMap
✓ It stores key-value pairs, where each key is unique and maps to
a specific value.
HashMap
✓ The HashMap uses a hash table for internal storage, which
allows for fast retrieval, insertion, and deletion of key-value
pairs.
Constructor Description
HashMap() Creates an empty HashMap with an initial capacity of 16
HashMap(int capacity) Creates an empty HashMap with the specified initial capacity.
Characteristics of HashMap
✓ Unordered: The elements in a HashMap are unordered. It does not guarantee any
specific order of the keys or values.
✓ Key-Value Pair: A HashMap stores data in the form of key-value pairs, where the key is
unique and the value can be duplicated.
✓ Resizing: HashMap automatically grows as elements are added.
✓ Null Keys and Values: A HashMap allows one null key and any number of null values.
✓ Non-Synchronized: HashMap is not synchronized.
✓ Efficiency: Operations like insertion, deletion, and lookup are performed in constant time,
i.e., O(1) on average, assuming a good hash function.
✓ Allows Duplicate Values: While keys must be unique, values can be duplicated across
different keys.
Methods of HashMap
✓ put(K key, V value): Adds the specified key-value pair to the map. If the key already
exists, it updates the value.
✓ get(Object key): Retrieves the value associated with the specified key, null otherwise.
✓ remove(Object key): Removes the key-value pair associated with the specified key.
✓ containsKey(Object key): Checks if the map contains the specified key.
✓ containsValue(Object value): Checks if the map contains the specified value.
✓ size(): Returns the number of key-value pairs in the map.
✓ isEmpty(): Returns true if the map is empty, otherwise false.
✓ keySet(): Returns a set of all the keys in the map.
✓ values(): Returns a collection of all the values in the map.
✓ entrySet(): Returns a set of all key-value pairs in the map as [Link] objects.
// Iterate over Map
HashMap Example Set<String> fruites = [Link]();
for(String fn : fruites){
import [Link]; [Link](fn+" : "+ [Link](fn));
import [Link]; }
// Check if a key exists
public class Ex4 { [Link]("Contains key 'Banana'? " +
public static void main(String[] args) { [Link]("Banana")); // Output: true
// Create a HashMap(fruit, price)
HashMap<String, Integer> map = new HashMap<>(); // Check if a value exists
[Link]("Contains value 40? " +
// Add key-value pairs [Link](40)); // Output: true
[Link]("Apple", 120);
[Link]("Banana", 40); // Remove a key-value pair
[Link]("Orange", 150); [Link]("Orange");
duplicate values.
HashSet
✓ Since it does not maintain any order, the elements in a
HashSet are unordered.
Constructor Description
HashSet() Creates a default HashSet with an initial capacity of 16.
HashSet(int initialCapacity) Creates a HashSet with the specified initial capacity.
Characteristics of HashSet
List Set
The list allows duplicate elements The set doesn’t allow duplicate elements.
Elements by their position can be accessed. Position access to elements is not allowed.
Multiple null elements can be stored. Null elements can store only once.