【发布时间】:2018-10-19 19:17:43
【问题描述】:
我在网上遇到了这个练习,我有两个类,我应该使 Tutor 类不可变。但是,我唯一能想到的是将final 添加到name 字段。对于构造函数,我认为我不需要更改 name 变量的初始化,因为 String 是不可变的。我不确定如何处理集合以及如何使构造函数的这一部分不可变。 根据练习,我不应该更改 Student 类(我可以看到它是可变的)
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;
}
}
【问题讨论】:
-
可能重复? link
-
导师名称仍然可以在导师类本身内更改,因此可能不被认为是不可变的。也许也可以尝试将字符串名称设为
final。顺便说一句,您应该知道在类定义上设置final意味着该类不能是extended。虽然不会使类不可变
标签: java immutability