Usually, you will not want to retrieve an element in a set when you already have it. You might to remove your element from a set, or know if it belongs to a set, thats all. Know want you want to do is to index your students by grade, so the index is the grade, not the object itself. Map is the solution.
If I were you, I would use the following structure which retrieves all students with the
same grade quickly (they are sorted by grades too) :
private SortedMap<Integer,Set<Student>> _studentsByGrade = new TreeMap<Integer,Set<Student>>();
public void updateStudent(Student student, int oldGrade, int newGrade)
{
getOrCreateContainer(oldGrade).remove(student);
getOrCreateContainer(newGrade).add(student);
student.setGrade(newGrade);
}
public Set<Student> getOrCreateContainer(int grade)
{
Set<Student> set = _studentsByGrade.get(grade);
if(set==null)
{
set = new HashSet<Student>();
_studentsByGrade.put(grade, set);
}
return set;
}
Don't forget to overload the equals and hashcode in your Student class to make it work correctly.
You might also want to check the cqengine library if you want to perform java indexations easily and fast, but the solution presented above is just ok for your usage.