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; }
}
是否可以做更多的事情来使这个类不可变?字符串已经是不可变的,返回的集合是不可修改的。tutees 和 name 变量是私有的和最终的。还能做什么?如果使用 Tutor 类的唯一类在包中,我可以将构造函数、getTutees 方法和 getName 方法更改为包私有吗?
编辑:
这是 Student 类,问题要求我描述必要的更改以使 Student 不可变。我已经注释掉了两个 setter 方法,所以我可以使变量成为最终的。这是使它真正不可变的唯一方法吗?
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; }
}