public class Student implements java.io.Serializable {

private long studentId;
private String studentName;
private Set<Course> courses = new HashSet<Course>(0);

public Student() {
}

public Student(String studentName) {
    this.studentName = studentName;
}

public Student(String studentName, Set<Course> courses) {
    this.studentName = studentName;
    this.courses = courses;
}

public long getStudentId() {
    return this.studentId;
}

public void setStudentId(long studentId) {
    this.studentId = studentId;
}

public String getStudentName() {
    return this.studentName;
}

public void setStudentName(String studentName) {
    this.studentName = studentName;
}

public Set<Course> getCourses() {
    return this.courses;
}

public void setCourses(Set<Course> courses) {
    this.courses = courses;
}

}

在这里,他们使用 Hashset 来获取类(class)。我的疑问是我可以使用列表来获取
类(class)在这里。我在互联网上读到该列表以指定的顺序获取 vaues 并允许
列表中的重复项。而在集合中它没有任何顺序并且不允许
重复。我想知道我应该在哪里使用集合和列表?任何人都可以建议吗?

最佳答案

感觉就像你已经回答了你自己的问题。如果您需要一个项目集合,并且您希望项目集合没有重复项,请使用集合。您可以使用 SortedSet 强加排序。

如果您的集合允许有重复项,那么您可以使用 List。我认为在您的示例中, Set 有效,因为学生可能永远不会两次参加同一门类(class)。

10-06 11:12