IamIronMAN
IamIronMAN

Reputation: 1879

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?

Upvotes: 4

Views: 646

Answers (2)

NG.
NG.

Reputation: 22914

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.

Upvotes: 6

Bozho
Bozho

Reputation: 597344

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

Note that preserving order is not impossible for a Set - there are implementations (like LinkedHashSet) that preserve the order of elements, and other, like TreeSet, which keep to elements sorted.

Upvotes: 3

Related Questions