Is lesson me hum seekhenge:
- Set kya hota hai
- Set ki properties
- Set implementations (HashSet, LinkedHashSet, TreeSet)
- Important methods
- Real examples
Set ek interface hai jo:
unique elements store karta hai
Features:
✔ duplicate elements allowed nahi
✔ unordered collection (mostly)
✔ null ek hi allow hota hai (HashSet me)
java.util.Set
Java me main Set implementations:
HashSet
LinkedHashSet
TreeSet
✔ unordered
✔ fast (hashing use karta hai)
✔ duplicate remove automatically
Example:
import java.util.*;
class Test {
public static void main(String[] args){
HashSet<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10); // duplicate ignore
System.out.println(set);
}
}✔ insertion order maintain karta hai
✔ thoda slow HashSet se
Example:
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("A");
set.add("B");
set.add("C");
System.out.println(set);✔ sorted order me elements store karta hai
✔ internally tree structure use karta hai
Example:
TreeSet<Integer> set = new TreeSet<>();
set.add(30);
set.add(10);
set.add(20);
System.out.println(set); // sorted output| Method | Use |
|---|---|
| add() | element add |
| remove() | delete |
| contains() | check element |
| size() | count |
| clear() | remove all |
for(int n : set){
System.out.println(n);
}| Feature | Set | List |
|---|---|---|
| Duplicate | ❌ No | ✔ Yes |
| Order | ❌ No (HashSet) | ✔ Yes |
| Index | ❌ No | ✔ Yes |
| Set Type | Null Allowed |
|---|---|
| HashSet | ✔ Yes (1 time) |
| LinkedHashSet | ✔ Yes |
| TreeSet | ❌ No |
unique values store karna
Example:
usernames
emails
IDs
✔ Set duplicates automatically remove karta hai
✔ HashSet fastest hota hai
✔ TreeSet sorted data deta hai
- Set kya hota hai?
- HashSet aur TreeSet me difference?
- Set me duplicate kyun allowed nahi?
- TreeSet me null kyun allowed nahi?
Is lesson me humne seekha:
✔ Set interface
✔ HashSet, LinkedHashSet, TreeSet
✔ Important methods
✔ Differences aur use cases
Set Java me unique data store karne ke liye best collection hai.