package main;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public final class Tutor {
private final String name;
private final Set<Student> tutees;
public Tutor(String name, Student[] students) {
this.name = name;
this.tutees = new HashSet<Student>();
for (int i = 0; i < students.length; i++) {
tutees.add(students[i]);
}
}
public Set<Student> getTutees() { return Collections.unmodifiableSet(tutees); }
public String getName() { return name; }
}
Is there more that could be done to make this class immutable? String is already immutable, the set is returned unmodifiable. The tutees and name variables are private and final. What else could be done? If the only classes using the Tutor class were within the package, could I change the constructor, getTutees method and getName method to package-private?
Edit:
Here is the Student class, the question asked me to describe the necessary changes to also make Student immutable. I have commented out both setter methods so I can make the variables final. Is this the only way to make it truly immutable?
public final class Student {
private final String name;
private final String course;
public Student(String name, String course) {
this.name = name;
this.course = course;
}
public String getName() { return name; }
public String getCourse() { return course; }
//public void setName(String name) { this.name = name; }
//public void setCourse(String course) { this.course = course; }
}
Immutables is a handy toolkit for making immutable objects in Java. If you build your entire domain using it, it will be immutable. It takes the question of 'Is this object immutable' out of the equation.