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 use the Hashset to get courses. My doubt is that I can use the list to get courses here. I read on the Internet that the list gets the vases in that order and allows duplicates inside the list. whereas in the kit it has no order and will not allow duplicates. I want to know where should I use sets and lists? Can anyone suggest?

+4
source share
2 answers

Looks like you already answered your question. If you need a collection of items, and you want to avoid duplicates in the collection of items, use the kit. You can use SortedSet to put order.

If your collection is allowed to have duplicates, you can use the List. I think the set works in your example, since the student will probably never repeat the same course twice.

+6
source

The fundamental difference between List and Set (as you said) means that Set does not allow duplication, but List . So in your case, a Set more appropriate, since the student should not be able to enroll in the course twice. Actually, he should be able, but in the same semester. Thus, each student can have a set of CourseEnrollment objects, not Course objects.

Note that saving order is not impossible for Set - there are implementations (for example, LinkedHashSet ) that preserve the order of elements, and others, such as TreeSet , that preserve for sorted elements.

+3
source

All Articles