Skip to content

Commit 2459e6d

Browse files
feat: add MCQ quiz and student grade manager implementation with appropriate collections
1 parent 271d064 commit 2459e6d

File tree

3 files changed

+471
-0
lines changed

3 files changed

+471
-0
lines changed

module02-collections/answers.md

Lines changed: 298 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,298 @@
1+
# Module 02: Collections - Answers
2+
3+
## MCQ Quiz Answers
4+
5+
### 1. Which collection allows duplicate elements and maintains insertion order?
6+
**Answer: c) ArrayList**
7+
*Explanation: ArrayList allows duplicates and maintains insertion order. HashSet doesn't allow duplicates, TreeSet doesn't maintain insertion order.*
8+
9+
### 2. What is the time complexity of adding an element to a HashMap?
10+
**Answer: a) O(1) average case**
11+
*Explanation: HashMap uses hash table with O(1) average time complexity for basic operations.*
12+
13+
### 3. Which collection is best for implementing a LIFO (Last In, First Out) structure?
14+
**Answer: c) Stack**
15+
*Explanation: Stack is specifically designed for LIFO operations with push() and pop() methods.*
16+
17+
### 4. What happens when you try to add a duplicate element to a TreeSet?
18+
**Answer: c) It ignores the duplicate**
19+
*Explanation: TreeSet doesn't allow duplicates. It uses compareTo() or Comparator to detect duplicates.*
20+
21+
### 5. Which interface does not extend Collection interface?
22+
**Answer: d) Map**
23+
*Explanation: Map is a separate interface that doesn't extend Collection. It represents key-value pairs.*
24+
25+
### 6. What is the main difference between ArrayList and LinkedList?
26+
**Answer: b) ArrayList uses array, LinkedList uses doubly-linked nodes**
27+
*Explanation: ArrayList uses resizable array for storage, LinkedList uses doubly-linked nodes.*
28+
29+
### 7. Which method is used to iterate over a Map's key-value pairs?
30+
**Answer: c) entrySet()**
31+
*Explanation: entrySet() returns a Set of Map.Entry objects, allowing iteration over key-value pairs.*
32+
33+
### 8. What does the Collections.sort() method require from the elements?
34+
**Answer: b) Elements must implement Comparable or provide a Comparator**
35+
*Explanation: Sorting requires a way to compare elements, either through Comparable interface or a Comparator.*
36+
37+
### 9. Which collection provides O(1) insertion and deletion at both ends?
38+
**Answer: c) ArrayDeque**
39+
*Explanation: ArrayDeque provides O(1) operations at both ends, making it ideal for queue and stack operations.*
40+
41+
### 10. What is the difference between fail-fast and fail-safe iterators?
42+
**Answer: b) Fail-fast throws exception on modification, fail-safe works on copy**
43+
*Explanation: Fail-fast iterators throw ConcurrentModificationException, fail-safe work on a copy of the collection.*
44+
45+
---
46+
47+
## Student Grade Manager Solution
48+
49+
```java
50+
import java.util.*;
51+
import java.util.stream.Collectors;
52+
53+
// Student class with proper equals and hashCode
54+
public class Student {
55+
private String studentId;
56+
private String name;
57+
58+
public Student(String studentId, String name) {
59+
this.studentId = studentId;
60+
this.name = name;
61+
}
62+
63+
// Getters
64+
public String getStudentId() { return studentId; }
65+
public String getName() { return name; }
66+
67+
// Override equals and hashCode based on studentId
68+
@Override
69+
public boolean equals(Object obj) {
70+
if (this == obj) return true;
71+
if (obj == null || getClass() != obj.getClass()) return false;
72+
Student student = (Student) obj;
73+
return Objects.equals(studentId, student.studentId);
74+
}
75+
76+
@Override
77+
public int hashCode() {
78+
return Objects.hash(studentId);
79+
}
80+
81+
@Override
82+
public String toString() {
83+
return name + " (" + studentId + ")";
84+
}
85+
}
86+
87+
// GradeManager class using appropriate collections
88+
public class GradeManager {
89+
// HashSet to store unique students
90+
private Set<Student> students;
91+
// HashMap to map students to their grades
92+
private Map<Student, List<Integer>> grades;
93+
94+
public GradeManager() {
95+
this.students = new HashSet<>();
96+
this.grades = new HashMap<>();
97+
}
98+
99+
// Add a new student
100+
public boolean addStudent(Student student) {
101+
boolean added = students.add(student);
102+
if (added) {
103+
grades.put(student, new ArrayList<>());
104+
}
105+
return added;
106+
}
107+
108+
// Add a grade for a student
109+
public void addGrade(Student student, int grade) {
110+
// Validate grade range
111+
if (grade < 0 || grade > 100) {
112+
throw new IllegalArgumentException("Grade must be between 0 and 100");
113+
}
114+
115+
// Add student if not exists
116+
if (!students.contains(student)) {
117+
addStudent(student);
118+
}
119+
120+
grades.get(student).add(grade);
121+
}
122+
123+
// Get all grades for a student
124+
public List<Integer> getGrades(Student student) {
125+
List<Integer> studentGrades = grades.get(student);
126+
return studentGrades != null ? new ArrayList<>(studentGrades) : new ArrayList<>();
127+
}
128+
129+
// Calculate average grade for a student
130+
public double getAverageGrade(Student student) {
131+
List<Integer> studentGrades = grades.get(student);
132+
if (studentGrades == null || studentGrades.isEmpty()) {
133+
return 0.0;
134+
}
135+
136+
double sum = 0;
137+
for (int grade : studentGrades) {
138+
sum += grade;
139+
}
140+
return sum / studentGrades.size();
141+
}
142+
143+
// Get all students sorted by name
144+
public List<Student> getStudentsSortedByName() {
145+
List<Student> sortedStudents = new ArrayList<>(students);
146+
sortedStudents.sort(Comparator.comparing(Student::getName));
147+
return sortedStudents;
148+
}
149+
150+
// Find top N students by average grade
151+
public List<Student> getTopStudents(int n) {
152+
List<Student> allStudents = new ArrayList<>(students);
153+
154+
// Sort by average grade in descending order
155+
allStudents.sort((s1, s2) -> {
156+
double avg1 = getAverageGrade(s1);
157+
double avg2 = getAverageGrade(s2);
158+
return Double.compare(avg2, avg1); // Descending order
159+
});
160+
161+
// Return top N students
162+
return allStudents.subList(0, Math.min(n, allStudents.size()));
163+
}
164+
165+
// Alternative using Stream API (if you know streams)
166+
public List<Student> getTopStudentsWithStreams(int n) {
167+
return students.stream()
168+
.sorted((s1, s2) -> Double.compare(getAverageGrade(s2), getAverageGrade(s1)))
169+
.limit(n)
170+
.collect(Collectors.toList());
171+
}
172+
173+
// Display all students and their grades
174+
public void displayAllGrades() {
175+
for (Student student : getStudentsSortedByName()) {
176+
List<Integer> studentGrades = grades.get(student);
177+
System.out.printf("%s: %s (Average: %.2f)%n",
178+
student, studentGrades, getAverageGrade(student));
179+
}
180+
}
181+
182+
// Bonus: Remove student and all grades
183+
public boolean removeStudent(Student student) {
184+
boolean removed = students.remove(student);
185+
if (removed) {
186+
grades.remove(student);
187+
}
188+
return removed;
189+
}
190+
191+
// Bonus: Get class average
192+
public double getClassAverage() {
193+
if (students.isEmpty()) {
194+
return 0.0;
195+
}
196+
197+
double sum = 0;
198+
for (Student student : students) {
199+
sum += getAverageGrade(student);
200+
}
201+
return sum / students.size();
202+
}
203+
}
204+
205+
// Test class
206+
public class GradeManagerTest {
207+
public static void main(String[] args) {
208+
GradeManager manager = new GradeManager();
209+
210+
// Create students
211+
Student alice = new Student("S001", "Alice");
212+
Student bob = new Student("S002", "Bob");
213+
Student charlie = new Student("S003", "Charlie");
214+
215+
// Add students
216+
System.out.println("Adding students...");
217+
System.out.println("Alice added: " + manager.addStudent(alice));
218+
System.out.println("Bob added: " + manager.addStudent(bob));
219+
System.out.println("Charlie added: " + manager.addStudent(charlie));
220+
221+
// Try adding duplicate
222+
System.out.println("Alice added again: " + manager.addStudent(alice));
223+
224+
// Add grades
225+
System.out.println("\nAdding grades...");
226+
manager.addGrade(alice, 85);
227+
manager.addGrade(alice, 92);
228+
manager.addGrade(alice, 78);
229+
230+
manager.addGrade(bob, 90);
231+
manager.addGrade(bob, 88);
232+
233+
manager.addGrade(charlie, 95);
234+
manager.addGrade(charlie, 93);
235+
manager.addGrade(charlie, 97);
236+
237+
// Display results
238+
System.out.println("\nAll Grades:");
239+
manager.displayAllGrades();
240+
241+
System.out.println("\nStudents sorted by name:");
242+
for (Student student : manager.getStudentsSortedByName()) {
243+
System.out.println(student);
244+
}
245+
246+
System.out.println("\nTop 2 students:");
247+
for (Student student : manager.getTopStudents(2)) {
248+
System.out.printf("%s - Average: %.2f%n", student, manager.getAverageGrade(student));
249+
}
250+
251+
System.out.printf("\nAlice's average: %.2f%n", manager.getAverageGrade(alice));
252+
System.out.printf("Class average: %.2f%n", manager.getClassAverage());
253+
254+
// Test individual student grades
255+
System.out.println("\nAlice's grades: " + manager.getGrades(alice));
256+
}
257+
}
258+
```
259+
260+
## Alternative Implementation Using TreeMap (Bonus)
261+
262+
```java
263+
// Version that automatically keeps students sorted by name
264+
public class SortedGradeManager {
265+
// TreeMap automatically sorts by key (requires Student to implement Comparable)
266+
private Map<Student, List<Integer>> grades;
267+
268+
public SortedGradeManager() {
269+
// Sort students by name automatically
270+
this.grades = new TreeMap<>(Comparator.comparing(Student::getName));
271+
}
272+
273+
public void addGrade(Student student, int grade) {
274+
grades.computeIfAbsent(student, k -> new ArrayList<>()).add(grade);
275+
}
276+
277+
public Set<Student> getAllStudents() {
278+
return grades.keySet(); // Already sorted by name
279+
}
280+
281+
// Other methods similar to above...
282+
}
283+
```
284+
285+
## Key Collection Concepts Demonstrated:
286+
287+
1. **HashSet**: Used for storing unique students
288+
2. **HashMap**: Used for mapping students to their grades
289+
3. **ArrayList**: Used for storing grades (allows duplicates, maintains order)
290+
4. **TreeMap**: Bonus implementation for automatic sorting
291+
5. **Comparator**: Used for custom sorting
292+
6. **Stream API**: Modern approach for filtering and sorting
293+
7. **equals() and hashCode()**: Proper implementation for custom objects in collections
294+
295+
This solution shows how to choose appropriate collection types based on requirements:
296+
- **Set** for uniqueness
297+
- **Map** for key-value relationships
298+
- **List** for ordered, duplicate-allowing collections

module02-collections/task1.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# Module 02: Collections - MCQ Quiz
2+
3+
## Choose the best answer for each question:
4+
5+
### 1. Which collection allows duplicate elements and maintains insertion order?
6+
a) HashSet
7+
b) TreeSet
8+
c) ArrayList
9+
d) HashMap
10+
11+
### 2. What is the time complexity of adding an element to a HashMap?
12+
a) O(1) average case
13+
b) O(log n)
14+
c) O(n)
15+
d) O(n²)
16+
17+
### 3. Which collection is best for implementing a LIFO (Last In, First Out) structure?
18+
a) ArrayList
19+
b) LinkedList
20+
c) Stack
21+
d) Queue
22+
23+
### 4. What happens when you try to add a duplicate element to a TreeSet?
24+
a) It throws an exception
25+
b) It adds the duplicate
26+
c) It ignores the duplicate
27+
d) It replaces the existing element
28+
29+
### 5. Which interface does not extend Collection interface?
30+
a) List
31+
b) Set
32+
c) Queue
33+
d) Map
34+
35+
### 6. What is the main difference between ArrayList and LinkedList?
36+
a) ArrayList is synchronized, LinkedList is not
37+
b) ArrayList uses array, LinkedList uses doubly-linked nodes
38+
c) ArrayList allows duplicates, LinkedList doesn't
39+
d) No difference in functionality
40+
41+
### 7. Which method is used to iterate over a Map's key-value pairs?
42+
a) keySet()
43+
b) values()
44+
c) entrySet()
45+
d) iterator()
46+
47+
### 8. What does the Collections.sort() method require from the elements?
48+
a) Elements must implement Serializable
49+
b) Elements must implement Comparable or provide a Comparator
50+
c) Elements must be numeric
51+
d) Elements must override toString()
52+
53+
### 9. Which collection provides O(1) insertion and deletion at both ends?
54+
a) ArrayList
55+
b) LinkedList
56+
c) ArrayDeque
57+
d) Vector
58+
59+
### 10. What is the difference between fail-fast and fail-safe iterators?
60+
a) Fail-fast works with modifications, fail-safe doesn't
61+
b) Fail-fast throws exception on modification, fail-safe works on copy
62+
c) No difference
63+
d) Fail-safe is only for synchronized collections

0 commit comments

Comments
 (0)