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 can Comparator order Student objects by different fields?ComputerScienceOne · Comparators
- How does a Comparator determine the order of two elements?ComputerScienceOne · Comparators
- What are sorted collections in the Java Collections framework?ComputerScienceOne · Sorted Collections
- Why are equals() and hashCode() important when searching and using sets?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- How can lambda expressions build a multi-field Comparator?ComputerScienceOne · Java 8: Lambda Expressions
- How can method references and Comparator methods make ordering more concise?ComputerScienceOne · Java 8: Lambda Expressions
- How can a Java Comparator handle null values?ComputerScienceOne · Importance of javaequals() and javahashCode() Methods
- What is the difference between Comparable and Comparator in Java?ComputerScienceOne · Comparators