Bifalgorithm post · Computer science one · Handling javanull values

How should a Comparator order elements in a SortedSet?

How should a Comparator order elements in a SortedSet? (Computer science one · Handling javanull values) — "6 //sortedInts has elements 30, 20, 10 in descendin…

Ideas in this flowchart

  • SortedSet relies on a Comparator that orders elements consistently.
  • A SortedSet is still a Set and does not allow duplicate elements.
  • If the Comparator returns zero, the attempted element is not inserted.
  • The byName Comparator orders Student objects by first name and last name.
  • Two distinct students may both be named John Doe but have different IDs.
  • The byName Comparator returns zero for those students because their names match.
  • Only one of the students can exist in the SortedSet.
  • Comparators must break ties appropriately.
  • When names match, the Comparator should compare the students' IDs.
  • A TreeSet is created with the byName Comparator.
  • Students added to the SortedSet are ordered by name.
  • The loop prints each student from the sorted set.
  • The sorted integer example contains 30, 20, and 10 in descending order.
Feed/

How should a Comparator order elements in a SortedSet?

No cover

Channel

Computer science one

1 page

"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."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.