Write a final StudentRecord class with a name, roll number and a list of subject marks; make it fully immutable with defensive copies, and add withMark(subject, marks) that returns a new record.
Solution
Main.java
import java.util.LinkedHashMap;
import java.util.Map;
final class StudentRecord {
private final String name;
private final int roll;
private final Map<String, Integer> marks;
StudentRecord(String name, int roll, Map<String, Integer> marks) {
this.name = name;
this.roll = roll;
this.marks = java.util.Collections.unmodifiableMap(new LinkedHashMap<>(marks)); // copy, keep order, read-only
}
public String name() { return name; }
public int roll() { return roll; }
public Map<String, Integer> marks() { return marks; } // already read-only
public StudentRecord withMark(String subject, int m) {
Map<String, Integer> copy = new LinkedHashMap<>(marks);
copy.put(subject, m);
return new StudentRecord(name, roll, copy);
}
public double average() { return marks.values().stream().mapToInt(Integer::intValue).average().orElse(0); }
}
public class Main {
public static void main(String[] args) {
Map<String, Integer> input = new LinkedHashMap<>();
input.put("Maths", 90);
input.put("Physics", 78);
StudentRecord r1 = new StudentRecord("Asha", 12, input);
input.put("Maths", 0); // no effect on r1
StudentRecord r2 = r1.withMark("Chemistry", 84).withMark("Physics", 81);
String blocked;
try { r1.marks().put("Maths", 100); blocked = "changed"; } catch (UnsupportedOperationException e) { blocked = "blocked"; }
System.out.printf("%s %.1f | %s %.1f | %s%n", r1.marks(), r1.average(), r2.marks(), r2.average(), blocked);
}
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!