【发布时间】:2016-05-26 21:13:56
【问题描述】:
目前正在准备考试...在过去的论文中遇到了这个问题。
考虑以下学生和导师课程:
public class Student {
private String name;
private 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;
}
}
导师:
public final class Tutor {
private String name;
private final Set<Student> tutees;
public Tutor(String name, Student[] students) {
this.name = name;
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;
}
}
重写 Tutor 类以使其不可变(不修改 Student 类)。
我知道名称字段应该有final 修饰符以确保线程安全。
如果学生Set 包含可变的学生对象并且学生类不能更改,那么我们如何使该类不可变?也许创建一个 Set 的克隆并在每次调用 getTutees 方法时清除 tutees 并将克隆的元素添加到其中?
还是尽管集合包含可变对象,但它已经是不可变的?
【问题讨论】:
-
immutable 的定义有很多,所以只有测试的作者才知道它们的含义。也许他们不关心包含的对象。或者,当您返回不可修改的集合时,他们可能希望您创建学生的副本。
标签: java collections immutability mutable