-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path10-Collections.java
More file actions
132 lines (64 loc) · 2.01 KB
/
Copy path10-Collections.java
File metadata and controls
132 lines (64 loc) · 2.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
* Collection in Java?
👉 Collection means a group of objects.
In Java, the Collection Framework helps us store and manage data easily.
Example:
Instead of storing 100 variables, we store them inside a collection like ArrayList.
🔹 Main Types of Collections
- There are 3 important interfaces:
i] List – Allows duplicates, maintains order
ii] Set – No duplicates
iii] Map – Stores key-value pairs
1️⃣ List (ArrayList Example)
✔ Allows duplicate values
✔ Maintains insertion order
Example : import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
ArrayList<String> names = new ArrayList<>();
names.add("Yuva");
names.add("Yuvi");
names.add("Babloo");
System.out.println("Names in list:");
for(String name : names)
{
System.out.println(name);
}
}
}
2️⃣ Set (HashSet Example)
✔ Does NOT allow duplicates
✔ Order is not guaranteed
import java.util.HashSet;
public class Main
{
public static void main(String[] args)
{
HashSet<String> cities = new HashSet<>();
cities.add("Mysuru");
cities.add("Bangalore");
cities.add("Mysuru"); // duplicate
System.out.println("Cities:");
System.out.println(cities);
}
}
3️⃣ Map (HashMap Example)
✔ Stores data in key-value format
✔ Keys must be unique
import java.util.*;
public class MapExample
{
public static void main(String[] args)
{
HashMap<Integer, String> students = new HashMap<>();
students.put(1, "Yuvi");
students.put(2, "Babloo");
System.out.println(students);
}
}
| Feature | List | Set | Map |
| ---------- | ----- | ---- | --------- |
| Duplicates | ✅ Yes | ❌ No | ❌ Keys No |
| Order | ✅ Yes | ❌ No | ❌ No |
| Index | ✅ Yes | ❌ No | ❌ No |