The understanding of the red text in the screenshot is basically correct but not complete. As @jokester said, you did not post the entire code. Pay attention to the part before else on line 561. In fact, there are two cases for sorting TreeMap<T> or TreeSet<T>:
When created with Comparator<? super T>, then the sorting is based on this Comparator;
Create without Comparator<? super T>, then T must implement Comparable.
So looking at the situation of TreeSet<Person>, if it is created with Comparator<Person>, then Person does not need to implement Comparable at all.
In addition, Integer itself implements the Comparable type, and all basic types of encapsulated objects (as well as Long, Double, Boolean, etc.), as well as String, all implement Comparable, so of course it can be forced.
One last question for everyone, if a Comparator is used when creating a TreeMap, why do we need to specify the typeComparator<? super K>,而不是Comparator<K>或Comparator<? extends K>? See a constructor of TreeMap:
The understanding of the red text in the screenshot is basically correct but not complete. As @jokester said, you did not post the entire code. Pay attention to the part before else on line 561. In fact, there are two cases for sorting TreeMap<T> or TreeSet<T>:
When created with Comparator<? super T>, then the sorting is based on this Comparator;
Create without Comparator<? super T>, then T must implement Comparable.
So looking at the situation of TreeSet<Person>, if it is created with Comparator<Person>, then Person does not need to implement Comparable at all.
In addition, Integer itself implements the Comparable type, and all basic types of encapsulated objects (as well as Long, Double, Boolean, etc.), as well as String, all implement Comparable, so of course it can be forced.
One last question for everyone, if a Comparator is used when creating a TreeMap, why do we need to specify the type
Comparator<? super K>
,而不是Comparator<K>
或Comparator<? extends K>
? See a constructor of TreeMap:public TreeMap(Comparator<? super K> comparator);
Correct
Because
class Integer implements Comparable<Integer>