Collections in Java
Understanding Java Collections Framework
Introduction
Collections in Java are used to store, retrieve, and manipulate groups of objects.
The Java Collections Framework (JCF) provides a unified architecture for working with collections.
Key benefits:
Reduces programming effort
Increases performance
Promotes code reusability
What is the Collections Framework?
A set of interfaces, classes, and algorithms to handle groups of objects.
Part of java.util package.
Key components:
Interfaces (e.g., List, Set, Queue, Map)
Classes (e.g., ArrayList, HashSet, LinkedList, HashMap)
Algorithms (e.g., sorting, searching)
Hierarchy of Collections Framework
• Collection Interface (Root interface)
• List (Ordered, allows duplicates)
• ArrayList, LinkedList, Vector
• Set (No duplicates)
• HashSet, LinkedHashSet, TreeSet
• Queue (FIFO order)
Collections vs. Arrays
Common Collection Methods
• add() / addAll() → Add elements
• remove() / removeAll() → Delete elements
• size() → Get collection size
• contains() → Check if element exists
• iterator() → Traverse elements
• sort() → Sort elements (using Collections.sort())
Example:
List<Integer> numbers = new ArrayList<>(Arrays.asList(5, 3, 8));
Collections.sort(numbers); // [3, 5, 8]
When to Use Which Collection?
• ArrayList → Frequent access, less insertion/deletion.
• LinkedList → Frequent insertions/deletions.
• HashSet → Unique elements, no order needed.
• TreeSet → Unique elements, sorted order.
• HashMap → Fast key-value pairs.
• TreeMap → Sorted key-value pairs.
Advantages of Collections
1. Reusability → Ready-made data structures.
2. Type Safety → Generics prevent runtime errors.
3. Efficiency → Optimized algorithms.
4. Interoperability → Standardized methods.