I want to do a SET or LIST without duplicates, but also want access your index. For exemple: setvariable.get(0).getName(). To access the object.
In java documentation is not recommended that use conditions to eliminate the duplicates in a list. Then, how could i do?
I'm trying create an association between two objects, course and student. But i don't want that both to have duplicated data.
Thank you very much in advance!
CodePudding user response:
You don't want that there are duplicates in the combinations or each list should not contain any duplicates?
For the second option you can check your list by using .contains before adding any additional element:
List<String> testList = null;
String element = null;
if (testList.contains(element)) {
testList.add(element);
}
CodePudding user response:
I was going to explain that Java doesn't have an "indexable" set class ... but then I looked at what you are actually trying to implement.
I going to assume that the association you are trying to implement is many-to-many. In the real world, a student may take many courses, and a course may be taken by many students. I assume your are trying to model that in your program.
The natural way to represent a (queryable) many-to-many association between two Java classes is using a pair of Map
objects; e.g.
Map<Student, Set<Course>> enrolledCourses;
Map<Course, Set<Student>> enrolledStudents;
Depending on the kind of queries you need to perform, the maps could be HashMap
or TreeMap
. Each time you add or remove a relation between a Student
and a Course
you will need to update both Map
objects.
Assuming that you maintain the maps correctly, there won't be any duplicate copies of either Student
or Course
objects.
On the other hand, if the association doesn't need to be queryable, you can get away with Set
valued fields; e.g.
// In the Course class
Set<Student> enrolledStudents;
// In the Student class
Set<Course> enrolledCourses;
You could also use a List
class and use contains
to remove duplicates manually. That will lead to O(N)
insertion and deletion operations, but that may be acceptable under normal real world assumptions. (Course enrollment numbers will typically be capped, and a student will only be allowed to enroll in a limited number of courses.)
Note that your idea of using list positions as some kind of identifier is not practical. When you remove an element in the middle of a list, all following elements in the list change positions. Positions are not stable in the long term.