java - TreeSet的自然排序问题,也与多态有关
高洛峰
高洛峰 2017-04-18 10:51:00
0
2
566

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
黄舟

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>:

  1. When created with Comparator<? super T>, then the sorting is based on this Comparator;

  2. 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:

public TreeMap(Comparator<? super K> comparator);

迷茫
  1. Correct

  2. Because class Integer implements Comparable<Integer>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template