The Collection Framework in Java provides classes and interfaces to store, manage, and manipulate groups of objects efficiently.
A Collection in Java is a framework providing an architecture to store and manage a group of objects. It includes interfaces (List, Set, Queue, Map) and classes (ArrayList, HashSet, LinkedList, etc.) for efficient data handling.
import java.util.ArrayList;
import java.util.List;
public class ListExample {
public static void main(String[] args) {
List fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
System.out.println(fruits);
}
}
import java.util.HashSet;
import java.util.Set;
public class SetExample {
public static void main(String[] args) {
Set numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(10); // duplicate ignored
System.out.println(numbers);
}
}
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
Map marks = new HashMap<>();
marks.put("Alice", 90);
marks.put("Bob", 85);
System.out.println(marks);
}
}
The framework aims to:
- Represent and manipulate dynamic data groups efficiently
- Reduce programming effort using reusable data structures
- Provide high-performance, flexible data handling
- Reduces development time
- Provides ready-to-use data structures
- Improves performance with built-in algorithms
- Can increase memory overhead in some cases
- Type safety issues in non-generic collections
- Performance trade-offs with certain operations
The core interfaces include:
- List: Ordered collection, allows duplicates (ArrayList, LinkedList)
- Set: Unordered, no duplicates (HashSet, TreeSet)
- Queue: FIFO structure (PriorityQueue, LinkedList)
- Map: Stores key-value pairs (HashMap, TreeMap)
- Always use generics for type safety
- Choose the right collection class for your use case
- Prefer interfaces over concrete classes (List, Set, Map)
- Use streams and lambda expressions for cleaner, modern code