0
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; }  
}
4

3 回答 3

3

作为一个小的优化,你可以让它tutees不可变,所以它甚至不能在内部改变Tutor

public Tutor(String name, Student[] students) {
    this.name = name;
    Set<Student> tuts = new HashSet<>();
    for (Student student : students) {
        tuts.add(student);
    }
    this.tutees = Collections.unmodifiableSet(tuts);
}
public Set<Student> getTutees() { return this.tutees; }

较短的版本:

public Tutor(String name, Student[] students) {
    this.name = name;
    this.tutees = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(students)));
}
public Set<Student> getTutees() { return this.tutees; }
于 2015-08-20T02:55:12.150 回答
2

您的班级的不变性仅取决于班级的不变性Student。如果Student是不可变的,那么Tutor就是不可变的,反之亦然。确保类的不变性不需要其他任何东西Tutor

关于能见度。如果您的类仅在包中使用,则 make 是包私有的(在类级别上)。将公共方法公开。

于 2015-08-20T02:57:20.257 回答
1

Immutables是一个方便的工具包,用于在 Java 中制作不可变对象。如果您使用它构建整个域,它将是不可变的。它排除了“这个对象是否不可变”的问题。

于 2015-08-20T03:50:06.420 回答