Collections Framework in Java
In this lesson: Java Collections Framework explained — ArrayList, LinkedList, HashSet, HashMap — when to use which, with code. In Hindi & English.
What is the Collections Framework
The Collections Framework is a set of ready-made classes for storing groups of objects. Instead of building your own data structures, you use proven ones like ArrayList, HashSet and HashMap. They are grouped under three main ideas: List, Set and Map.
Why use it over arrays
- Grows automatically — no fixed size like an array.
- Built-in operations — add, remove, search and sort with ready methods.
- Many structures — pick a List, Set or Map to fit the job.
Arrays are fine for fixed-size data, but collections are far more flexible for real programs.
List
import java.util.ArrayList;
ArrayList<String> names = new ArrayList<>();
names.add("Aman");
names.add("Diya");
names.add("Aman"); // duplicates allowed
System.out.println(names);
A List keeps items in order and allows duplicates. ArrayList is the most common List — it grows as you add, and you access items by index.
Set
import java.util.HashSet;
HashSet<String> ids = new HashSet<>();
ids.add("A1");
ids.add("A2");
ids.add("A1"); // duplicate ignored
System.out.println(ids.size());
A Set stores only unique items — duplicates are dropped automatically. HashSet is the common choice, great for removing duplicates or checking membership fast.
Map
import java.util.HashMap;
HashMap<String, Integer> marks = new HashMap<>();
marks.put("Aman", 88);
marks.put("Diya", 92);
System.out.println(marks.get("Diya"));
A Map stores key-value pairs, so you look up a value by its key. HashMap is the common choice, giving fast lookup — perfect for name-to-marks or id-to-object.
Choosing the right one
| Need | Use |
|---|---|
| Ordered list, duplicates OK | ArrayList (List) |
| Only unique values | HashSet (Set) |
| Look up by a key | HashMap (Map) |
| Sorted order | TreeSet / TreeMap |
Common mistakes
- Using primitives. Collections store objects — use
<Integer>, not<int>. - Expecting order from a HashSet/HashMap. They do not keep insertion order.
- Forgetting the import. Import from
java.util. - Choosing the wrong type. Match List/Set/Map to whether you need order, uniqueness or keys.
Summary
- The Collections Framework provides ready data structures for objects.
- List (ArrayList) keeps order and allows duplicates.
- Set (HashSet) stores only unique items.
- Map (HashMap) stores key-value pairs for fast lookup.
- Collections grow automatically and offer many built-in methods.
Next, compare lists in ArrayList vs LinkedList, or maps in HashMap vs Hashtable.
Frequently Asked Questions
What is the Collections Framework in Java?
What is the difference between List, Set and Map?
Why use collections instead of arrays?
What is the most commonly used collection?
Do collections store primitives?
ArrayList<Integer>, not ArrayList<int>. Autoboxing handles the conversion for you.