LearnFrenzy
Sign in Take a free test

Encapsulation · Encapsulation Programs · Question 7

Immutable student record with defensive copies in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

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);
    }
}

Output Verified by compiling and running

{Maths=90, Physics=78} 84.0 | {Maths=90, Physics=81, Chemistry=84} 85.0 | blocked

Copy in, read-only out and "withers" that return new objects make the record impossible to change after creation.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links