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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With