Object Oriented Programming in JavaUnit 99 min read
Java Collections Framework: Interfaces, Implementations & Algorithms
Unit 9 of Object Oriented Programming in Java covers the Java Collections Framework (JCF), its core interfaces (List, Set, Map, Queue, Deque), key implementations (ArrayList, LinkedList, HashSet, TreeSet, HashMap, TreeMap, PriorityQueue), and utility classes (Collections, Arrays). Learn how to choose the right collecti
Core Concepts: Interfaces and Implementations
1. The Collections Framework Hierarchy
The JCF provides a unified architecture for storing and manipulating groups of objects. It consists of:
classDiagram
class Collection {
<<interface>>
+add(E e)
+remove(Object o)
+contains(Object o)
+iterator()
}
class List {
<<interface>>
+get(int index)
+add(int index, E e)
}
class Set {
<<interface>>
+no duplicates
}
class Queue {
<<interface>>
+offer(E e)
+poll()
}
class Map {
<<interface>>
+put(K key, V value)
+get(Object key)
}
Collection <|-- List
Collection <|-- Set
Collection <|-- Queue
Collection "1" --> "1" IteratorKey Interfaces:
List: Ordered collection (allows duplicates). Implementations:ArrayList,LinkedList,Vector.Set: No duplicates. Implementations:HashSet,LinkedHashSet,TreeSet.Map: Key-value pairs. Implementations:HashMap,LinkedHashMap,TreeMap.Queue/Deque: FIFO/LIFO operations. Implementations:PriorityQueue,ArrayDeque.
2. ArrayList vs. LinkedList: Trade-offs
| Feature | ArrayList | LinkedList |
|---|---|---|
| Underlying DS | Dynamic array | Doubly-linked list |
| Access Time | O(1) (random access) | O(n) |
| Insert/Delete | O(n) (shifting required) | O(1) (at head/tail) |
| Memory Overhead | Lower (stores only elements) | Higher (stores pointers + elements) |
| Thread Safety | No (use Collections.synchronizedList) |
No |
Visual: ArrayList Resizing When adding the 6th element (threshold), the array doubles in size (new capacity = 16) and copies all elements.
Real-World Applications
1. E-Sewa Transaction Queue
- Data Structure Used:
PriorityQueue(for urgent transactions) +HashMap(for user profiles). - How It Works:
- Transactions are stored in a
PriorityQueuewhere higher-priority payments (e.g., electricity bills) are processed first. - User details (e.g.,
userID: UserProfile) are stored in aHashMapfor O(1) access during verification. - Code Snippet:
PriorityQueue<Transaction> queue = new PriorityQueue<>(Comparator.comparingInt(Transaction::getPriority)); HashMap<String, User> users = new HashMap<>(); // Add a high-priority transaction queue.offer(new Transaction("user123", "electricity", 5));
- Transactions are stored in a
2. Daraz Order Processing
- Data Structure Used:
LinkedList(for order history) +HashSet(for tracking duplicate orders). - Why?:
- Orders are added to a
LinkedListto maintain insertion order (for user history). - A
HashSetchecks for duplicate orders in O(1) time to avoid fraud. - Example:
LinkedList<Order> orderHistory = new LinkedList<>(); HashSet<String> processedOrders = new HashSet<>(); if (!processedOrders.contains(orderId)) { orderHistory.add(new Order(orderId, "Laptop")); processedOrders.add(orderId); }
- Orders are added to a
3. Ncell Call Logs
- Data Structure Used:
TreeMap(sorted by call duration) +ArrayList(for unsorted logs). - Use Case:
TreeMapstores calls sorted by duration (for billing reports).ArrayListlogs all calls in real-time (for debugging).- Visual: TreeMap for Call Logs
Key Algorithms in Collections
1. Sorting a List
Algorithm: Use Collections.sort() (Timsort hybrid of merge sort + insertion sort) or list.sort() (Java 8+).
Time Complexity: O(n log n).
Example: Sorting City Names
List<String> cities = new ArrayList<>(Arrays.asList("Kathmandu", "Pokhara", "Lalitpur", "Bhaktapur"));
Collections.sort(cities); // Natural order
System.out.println(cities);
// Output: [Bhaktapur, Kathmandu, Lalitpur, Pokhara]
Trace Table:
| Step | cities Array |
Pivot | Comparison |
|---|---|---|---|
| 1 | ["Kathmandu", "Pokhara"] | "K" | "K" < "P" → swap |
| 2 | ["Pokhara", "Kathmandu"] | "P" | Merge subarrays |
| ... | ... | ... | ... |
2. Finding Duplicates in a Set
Use Case: Detect duplicate orders in Daraz or repeated logins in eSewa.
Solution: Use HashSet to track seen items.
List<String> orders = Arrays.asList("Laptop", "Phone", "Laptop", "Tablet");
Set<String> uniqueOrders = new HashSet<>(orders);
Set<String> duplicates = new HashSet<>(orders);
duplicates.removeAll(uniqueOrders); // {Laptop}
System.out.println("Duplicates: " + duplicates);
Visual: HashSet Collision Handling
3. PriorityQueue for Task Scheduling
Use Case: Pathao driver task assignment (highest-paying tasks first).
Implementation: PriorityQueue with a custom comparator.
PriorityQueue<Task> tasks = new PriorityQueue<>(
(t1, t2) -> Double.compare(t2.getPay(), t1.getPay())
);
tasks.offer(new Task("Deliver Pizza", 500.0));
tasks.offer(new Task("Grocery Run", 300.0));
System.out.println(tasks.poll().getDescription()); // "Deliver Pizza"
Trace Table:
| Step | Queue State | Polled Task |
|---|---|---|
| 1 | [Pizza(500), Grocery(300)] | Pizza(500) |
| 2 | [Grocery(300)] | Grocery(300) |
Utility Classes: Collections and Arrays
1. Collections Class Methods
| Method | Description | Example |
|---|---|---|
sort(List) |
Sorts a list in natural order. | Collections.sort(list) |
binarySearch(List, key) |
Searches a sorted list (O(log n)). | Collections.binarySearch(list, 5) |
reverse(List) |
Reverses the order of elements. | Collections.reverse(list) |
shuffle(List) |
Randomizes the order (for games/cards). | Collections.shuffle(deck) |
synchronizedList(List) |
Makes a thread-safe list. | List syncList = Collections.synchronizedList(new ArrayList()) |
Example: Binary Search
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
int index = Collections.binarySearch(numbers, 30); // Returns 2
2. Arrays Class Methods
| Method | Description | Example |
|---|---|---|
sort(array) |
Sorts an array. | Arrays.sort(arr) |
binarySearch(array, key) |
Searches a sorted array (O(log n)). | Arrays.binarySearch(arr, 5) |
asList(array) |
Converts array to a fixed-size list. | List list = Arrays.asList(arr) |
toString(array) |
Returns a string representation. | Arrays.toString(arr) |
Example: Converting Array to List
String[] cities = {"Kathmandu", "Pokhara", "Lalitpur"};
List<String> cityList = Arrays.asList(cities); // Fixed-size list!
Exam Tip
Interface vs. Implementation:
- Always declare variables as interfaces (e.g.,
List<String>), not implementations (ArrayList<String>). This makes code flexible. - Example:
// Good: Uses interface List<String> names = new ArrayList<>(); // Bad: Tight coupling ArrayList<String> names = new ArrayList<>();
- Always declare variables as interfaces (e.g.,
Time Complexity Questions:
- Memorize the Big-O of operations for each collection:
HashSet: O(1) foradd,contains(average case).TreeSet: O(log n) foradd,contains(sorted).ArrayList: O(1) forget(index), O(n) foradd/removein middle.
- Common Pitfall: Forgetting that
LinkedListhas O(n)get(index).
- Memorize the Big-O of operations for each collection:
Real-World Scenarios:
- Bank Loan Processing: Use
PriorityQueueto prioritize high-interest loans. - NEPSE Stock Tracking: Use
HashMap<String, Double>to store stock symbols and prices. - WhatsApp Chat History: Use
LinkedListto maintain message order (newest first).
- Bank Loan Processing: Use
Code Snippets for Exams:
- Always include import statements (e.g.,
import java.util.*;). - For sorting, show both
Collections.sort()andlist.sort()(Java 8+). - For duplicates, use
HashSet+removeAll().
- Always include import statements (e.g.,
Common Exam Questions:
- Differentiate between
List,Set, andMap. - Explain why
HashMapuses arrays + linked lists (for collision handling). - Write a program to reverse a list or find the second largest element in a
PriorityQueue.
- Differentiate between
Pro Tip: Practice implementing a custom Comparator for sorting objects (e.g., sorting Student objects by GPA). This is a frequent exam question!
Based on the TU BCA syllabus for Object Oriented Programming in Java (CACS204), unit 9.
Discussion
Loading…