Java Collections Framework
What is a Collection?
A collection is a group of items. In Java, a collection is used to store and work with many objects together.
Think about a shopping basket. You can put apples, bananas, or milk in it. You can also remove them or check if an
item is in the basket. Java collections work the same way.
Main Interfaces in the Java Collections Framework
- List: Stores items in order. Allows duplicates. Example: shopping list.
- Set: Stores unique items. No duplicates. Example: your T-shirt colors.
- Queue: Items in a line. First-in, first-out. Example: people in a bank line.
- Map: Stores key-value pairs. Like a dictionary. Example: phonebook (name → number).
Common Classes
- ArrayList (implements List): Fast for reading. Grows as needed.
- LinkedList (implements List & Queue): Good for adding/removing from the middle.
- HashSet (implements Set): No order. Fast look-up. Unique items.
- TreeSet (implements Set): Sorted items. Unique too.
- HashMap (implements Map): Fast key lookup. Keys are unique.
- TreeMap (implements Map): Sorted keys.
- PriorityQueue (implements Queue): Gives priority to items.
When to Use What?
- ArrayList: When you need to access items by index often.
- LinkedList: When you add/remove a lot from the middle.
- HashSet: When you care about fast lookup and uniqueness.
- TreeSet: When you also need sorting.
- HashMap: When you need to store items with a unique key.
- TreeMap: When you want the keys to stay sorted.
Examples from Daily Life
- List: Your shopping list. You can buy the same item twice.
- Set: Your list of unique hobbies.
- Map: Your contact list. A name (key) and phone number (value).
- Queue: A line at the ticket counter. First come, first served.
Code Examples
// Using ArrayList
List shoppingList = new ArrayList<>();
shoppingList.add("Milk");
shoppingList.add("Bread");
shoppingList.add("Milk"); // Duplicate allowed
// Using HashSet
Set uniqueHobbies = new HashSet<>();
uniqueHobbies.add("Reading");
uniqueHobbies.add("Swimming");
uniqueHobbies.add("Reading"); // Duplicate ignored
// Using HashMap
Map contacts = new HashMap<>();
contacts.put("Alice", "12345");
contacts.put("Bob", "67890");
// Using Queue
Queue bankLine = new LinkedList<>();
bankLine.add("Customer1");
bankLine.add("Customer2");
System.out.println(bankLine.poll()); // Customer1
Conclusion
Java Collections Framework makes it easy to handle groups of data. Choose the right collection for your task.
Practice a lot and try small projects!
Good luck and happy coding! 😊