Concept

How should a Comparator order elements in a SortedSet?

ComputerScienceOne / Handling javanull values

"6 //sortedInts has elements 30, 20, 10 in descending order\n\n7\n\n8 SortedSet<Student> sortedStudents = new TreeSet<Student>(byName);\n\n9 //add students, they will be sorted by name\n\n10 for(Student s : sortedStudents) {\n\n11 System.out.println(s);\n\n12 }\n\nWhen using a SortedSet it is important that the Comparator properly orders all elements. A SortedSet is still a Set : it does not allow duplicate elements. If the Comparator you use returns zero for any element that you attempt to insert, it will not be inserted. To demonstrate how this might fail, consider our byName Comparator for Student objects. Suppose two students have the same first name and last name, “John Doe” and “John Doe,” but have different IDs (as they are different people). The Comparator would return 0 for these two objects because they have the same first/last name, even though they are distinct people. Only one of these objects could exist in the SortedSet . To solve this problem, it is important to define Comparator s that “break ties” appropriately. In this case, we would want to modify the Comparator to return a comparison of IDs if the first and last name are the same."

Related Ideas

How should a Comparator order elements in a SortedSet? | ComputerScienceOne | Bifalgorithm | Bifalgorithm