Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can i use a set or List in this example?

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

}

Here they are using Hashset to get the courses. My doubt is can i use a list to get the courses here. I read in internet that list get the vaues in a specified order and allows duplicates inside the list. whereas in set it doesnt have any order and wont allow duplicates. I want to know where i should uses sets and lists? Can anyone suggest?

like image 325
IamIronMAN Avatar asked Jan 21 '23 08:01

IamIronMAN


1 Answers

It feels like you answered your own question already. If you need a Collection of items, and you want the collection of items to have no duplicates, use a Set. You can use a SortedSet to impose ordering.

If your collection is allowed to have duplicates, then you can use a List. I think in your example, a Set works since a student would probably never take the same course twice.

like image 75
NG. Avatar answered Jan 26 '23 09:01

NG.