Java Notes
Understand the Java Collections Framework from scratch — what it solves, the four main types (List, Set, Map, Queue), how each works, when to use which, with full explanations and examples.
Pehle ke Java mein agar tumhe 10 students ke names store karne the, tum likhte:
Lekin isme problem kya thi? Size fix tha. Agar 11 students aa gaye? Tumhe nayi array banani padti, sab copy karna padta. Aur agar beech se koi nikalna ho? Manual shifting. Agar duplicates nahi chahiye? Khud check karo. Agar key-value chahiye? Alag alag arrays — ek key ke liye, ek value ke liye.
Java Collections Framework ne ye sab problems solve ki. Ye ek ready-made kit hai data structures aur algorithms ki jisme:
- Resizable structures hain — khud grow aur shrink hoti hain
- Built-in operations hain — sorting, searching, filtering
- Type safety hai — Generics ki wajah se wrong type nahi daala ja sakta
- Common interface hai —
Listinterface pe kaam karo, baad meinArrayListseLinkedListswitch karo bina code change kiye
Collections Framework Sikhne Ka Sahi Approach
Directly ArrayList ya HashMap mein mat jaao. Pehle samjho:
- Problem kya hai? — Uniqueness chahiye? Order chahiye? Key-value chahiye? FIFO chahiye?
- Kaun sa type sahi hai? — List, Set, Map, ya Queue?
- Uska best implementation kaun sa hai? — ArrayList, LinkedList, HashSet, TreeSet...
Pehla Type: List — Ordered, Duplicates Allowed
List kya hota hai? Ek sequence jahan elements ek specific order mein hote hain. Same value baar baar ho sakti hai. Har element ka ek index hota hai — 0 se start hota hai.
Socho ek to-do list — items ek ke baad ek hain (ordered), ek hi kaam do baar aa sakta hai (duplicates), aur tum keh sakte ho "3rd item kya hai?" (indexed access).
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
List kab use karein: Jab order matter kare, duplicates allowed ho, ya index se access karna ho.
Common implementations: ArrayList (most used), LinkedList (frequent front/back operations ke liye)
Doosra Type: Set — Unique Elements Only
Set kya hota hai? Ek collection jahan koi duplicate nahi hota. Agar already existing element dobara add karo, silently ignore ho jaata hai. Mathematical set ki tarah.
Socho ek raffle draw — ek ticket number ek baar hi aana chahiye. Ya email addresses — koi email do baar registered nahi honi chahiye.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
add() return kya karta hai? boolean — true agar element naaya tha aur add hua, false agar duplicate tha.
Set kab use karein: Jab uniqueness guarantee karni ho. Jaise visited URLs, registered users, unique tags.
Common implementations: HashSet (fastest, no order), LinkedHashSet (insertion order), TreeSet (sorted)
Teesra Type: Map — Key-Value Pairs
Map kya hota hai? Har item do parts ka hota hai — ek key aur ek value. Key unique hoti hai. Ek key se tum directly uski value nikal sakte ho — bilkul dictionary ki tarah (word = key, meaning = value).
Socho student roll number aur naam — roll number unique hoga (key), aur naam use map karta hai (value). Tum poochho "Roll no 101 ka naam?" — directly milega.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Key uniqueness kya matlab hai? Agar same key dobara put() karo, purani value replace ho jaati hai. New entry nahi banti.
Map kab use karein: Jab kisi cheez ko key se lookup karna ho — word frequency, user data, configuration settings, caching.
Common implementations: HashMap (fastest), LinkedHashMap (insertion order), TreeMap (sorted keys)
Chautha Type: Queue — Processing Order
Queue kya hota hai? Ek line jahan jo pehle aaya wo pehle process hota hai — FIFO (First In, First Out). Ya kuch special queues mein jo zyada important hai wo pehle process hota hai.
Socho printer queue — documents ek line mein lagte hain, jo pehle aaya wo pehle print hoga. Ya hospital emergency — jo zyada seriously ill hai wo pehle dekhा jaata hai (priority queue).
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Queue kab use karein: Jab order mein process karna ho — task queues, BFS (graph traversal), print spooling, request handling.
Collections Utility Class — Ready-Made Algorithms
Collections (note: s ke saath) ek utility class hai jisme bahut saare ready-made algorithms hain. Ye methods static hain — directly class name se call karo.
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Sahi Collection Chunne Ka Simple Formula
Jab bhi naya collection chahiye, ye questions poochho:
Key-value store karna hai?
- Haan →
Mapuse karo - Sorted keys chahiye →
TreeMap - Insertion order chahiye →
LinkedHashMap - Bas fast lookup →
HashMap
Sirf unique values chahiye?
- Haan →
Setuse karo - Sorted chahiye →
TreeSet - Insertion order chahiye →
LinkedHashSet - Bas fast lookup →
HashSet
Ordered list chahiye, duplicates allowed?
- Queue/FIFO chahiye →
ArrayDequeyaLinkedList - Priority-based →
PriorityQueue - Random access by index →
ArrayList - Frequent front/back insert-delete →
ArrayDeque
Default choice: ArrayList aur HashMap — 80% cases mein ye kafi hain.
Collection vs Collections — Students Confuse Ho Jaate Hain
// Collection — ek INTERFACE hai (singular, no 's')
// java.util.Collection
// List, Set, Queue sab isko implement karte hain
// Ye define karta hai: add(), remove(), contains(), size(), etc.
import java.util.Collection;
Collection<String> c = new ArrayList<>(); // valid
// Collections — ek UTILITY CLASS hai (plural, with 's')
// java.util.Collections
// Iske methods static hain — algorithms provide karta hai
import java.util.Collections;
Collections.sort(list); // valid
Collections.shuffle(list);
Collections.unmodifiableList(list);Ek letter ka fark — ek interface, ek class. Interview mein aksar ye poochha jaata hai.
Common Mistake 1: For-Each Mein Remove
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Kyon fail hota hai? For-each internally Iterator use karta hai. Agar iteration ke dauran collection modify ho, Iterator detect karta hai (modCount check se) aur exception throw karta hai.
Common Mistake 2: Raw Types Use Karna
// WRONG — raw type, koi type safety nahi
List list = new ArrayList();
list.add("text");
list.add(42); // compile mein koi error nahi
list.add(3.14);
// Baad mein kisi bhi element par String operation karoge to runtime crash
// CORRECT — generic type specify karo
List<String> names = new ArrayList<>();
names.add("Asha");
// names.add(42); // COMPILE ERROR — baad ki problem nahi aayegiPractice Task
Task: Ek simple student management system banao:
List<String>mein 5 students ke naam add karoSet<String>mein check karo ki koi naam duplicate to nahiMap<String, Integer>mein har student ke marks store karoCollections.sort()se names alphabetically sort karo- Map iterate karke print karo: "Name: X, Marks: Y"
Hint: List ke names ko LinkedHashSet mein convert karo duplicate check ke liye. Map mein same names use karo.
Solution:
Try it in WoHoCode
Edit the program, then run it here.
Run this example to see its output.
Kya observe karo: nameList.size() 5 hai, uniqueNames.size() 4 hai — duplicate detect hua. Sorting sortedNames list ko modify karti hai — marks map untouched rehta hai. marks.get(name) ek naam ke baare mein marks nahi mila to null aayega (agar "Asha" ki duplicate entry ko filter nahi kiya hota to null issue aata).
Continue the lesson path