So I have a custom class Class that will have a set of another custom class Students. So it will look something like this:
public class Class {
private Set<Student> students;
// other methods
}
Now I will be adding and removing many students to the set students and i will also be changing many of the private fields of a student already in the set of students.
QUESTION: What data structure should I use to best implement this? Since I will be changing the property of the Student objects in set student (thereby changing the hashcodes) should I use an ArrayList instead?
It depends. As you are talking about student so must be there is somthing like id or rollno which is unique. If yes then override the hashcode method and implement the hashcode on the basis of their id's. Then there is no effect on the hashcode by changeing any of the other properties of student.
To chose Set or List is totaly depends upon your requirements. Read this link, and it will clarify the difference between Set and list
What is the difference between Set and List?
And if you are using objects in a Set then you can try to override both the hashcode and the equals method so that control of uniqueness is in you hands.
From your requirement, I thought the best structure should be Map. Set actually underlying uses the Map structure inside, and you also need taking care the equals method override for better lookup. And set and arraylist find the target object need take some find algorithm so it's not so efficient as you expected (especially in the very large collection situation). Even map will waste some space, but if your ID is some kind of primitive type, you could consider the primitive type of map implementation in the Trove library.
For a hashed collection such as
HashSet
, the key should beimmutable
. Hashset uses hashing internally to decide the bucket to store the object. And also while retrieving the object it will use hash to find the object bucket. If you are changing the object after storing, it may change the hashcode of the object and Set may not be able to retrieve the correct object. If you need to change the object even after adding it to the collection then using a hashed collection is not a good choice. Rather go forArraylist
, but note that withArrayList
you will lose the advantage to retrieve the desired Student quickly, as it could be with a Set.