🧺
Collections

Collections: List, Set, Map

Storing Groups of Data
💡 ArrayList is a train with its compartments in order (accessed by index). HashSet is a sticker album where no sticker repeats. HashMap is a locker room where every locker has its own name-tag (key).

ArrayList is an ordered list, duplicates allowed, accessed by index.

HashSet holds only unique values, no order guaranteed. HashMap stores key-value pairs — you can find a value instantly by its key, like a locker by name.

List<String> names = new ArrayList<>();
Set<Integer> ids = new HashSet<>();
Map<String, Integer> ages = new HashMap<>();
ages.put("Aarav", 10);
🧺
ArrayList is a train with its compartments in order (accessed by index). HashSet is a sticker album where no sticker repeats. HashMap is a locker room where every locker has its own name-tag (key).
1 / 5
On this page (5 subtopics)

Sabse upar "Collection" interface hai, jisse List, Set, aur Queue extend karte hain. Map is hierarchy ka part NAHI hai (kyunki wo key-value pairs store karta hai, single elements nahi) — wo apna alag interface (Map<K,V>) hai jo Collection extend nahi karta.

Har type ek different problem solve karta hai: List order + duplicates allow karta hai (jaise ek shopping list, order matter karta hai aur same item do baar ho sakta hai). Set sirf uniqueness ki guarantee deta hai (jaise ek class ke roll numbers — koi repeat nahi ho sakta). Queue processing order define karta hai (jaise ek ticket line — pehle aao, pehle jao). Map key-based fast lookup deta hai (jaise ek phonebook — naam se number dhoondo).

💡Tip: Interview mein "Collection vs Collections" poocha jaata hai — Collection (singular) ek interface hai (List/Set/Queue ka parent), Collections (plural) ek utility class hai jisme static helper methods hain (Collections.sort(), Collections.reverse(), etc.).

ArrayList List interface ki sabse commonly used implementation hai — internally ek resizable array hoti hai. add() element jodta hai (end mein by default, ya specific index par), get(index) retrieve karta hai (O(1) — bahut fast, direct array access jaisa), remove() index ya value se hata sakta hai, size() batata hai kitne elements hain.

contains() check karta hai value hai ya nahi (O(n) — linear search, kyunki ArrayList ko pata nahi kaha dhoondhe), isEmpty() batata hai khaali hai ya nahi, indexOf() value ka position dhoondta hai.

List<String> names = new ArrayList<>();
names.add("Aarav");
names.add("Riya");
System.out.println(names.get(0));   // Aarav
System.out.println(names.contains("Riya")); // true
names.remove("Aarav");
⚠️Common Mistake: ArrayList.contains() ya indexOf() O(n) time lete hain (poori list scan karte hain) — agar baar-baar "kya ye value hai" check karna hai bade dataset par, HashSet zyada fast hoga (O(1) average).

HashSet fastest hai (add/remove/contains sab average O(1)) lekin koi order guarantee nahi (hash-based storage, elements "random" order mein dikhte hain jab print karo). Zyadatar time ye hi best choice hai jab order matter na kare.

LinkedHashSet insertion order maintain karta hai (jis order mein add kiya, usi order mein iterate hoga) — thoda slower than HashSet (extra linked-list overhead), lekin predictable order chahiye to ye chuno.

TreeSet elements ko hamesha sorted (natural ya custom Comparator) order mein rakhta hai — internally ek balanced tree (Red-Black Tree) use karta hai, isliye operations O(log n) time lete hain (HashSet se slower, lekin sorted order milta hai automatically).

HashSetLinkedHashSetTreeSet
OrderKoi guarantee nahiInsertion orderSorted order
Speed (add/contains)O(1) averageO(1) averageO(log n)
Kab use kareinBas uniqueness chahiyeUniqueness + insertion orderUniqueness + sorted

HashMap har key ka hashCode() calculate karta hai, aur us hash ke basis par decide karta hai value kaha store hogi ("bucket" — internally ek array of buckets hoti hai). Yehi wajah hai key se value dhoondhna average O(1) (bahut fast) hota hai — array index jaisa direct jump, linear search nahi.

Agar do keys ka hash same aa jaaye ("collision"), wo ek hi bucket mein linked list (ya Java 8+ mein agar bahut zyada collisions ho, ek balanced tree) ki tarah store hoti hain — worst case thoda slow ho sakta hai, lekin achhe hashCode() implementation se ye rare hota hai.

HashMap null key allow karta hai (sirf ek), aur multiple null values. Isse Hashtable (purani, legacy class) alag hai jo koi null allow nahi karti.

Order chahiye + duplicates OK → ArrayList. Sirf unique values, order matter nahi → HashSet. Unique + insertion order chahiye → LinkedHashSet. Unique + sorted chahiye → TreeSet. Key se fast lookup chahiye → HashMap. Key se lookup + sorted keys chahiye → TreeMap.

ZarooratBest Choice
Ordered list, duplicates OKArrayList
Frequent insert/delete beech meinLinkedList
Sirf unique valuesHashSet
Unique + insertion orderLinkedHashSet
Unique + sortedTreeSet
Key-value, fast lookupHashMap
Key-value, sorted keysTreeMap
FIFO processingLinkedList (as Queue) / ArrayDeque