Home  >  Q&A  >  body text

java - TreeSet的自然排序问题,也与多态有关

高洛峰高洛峰2743 days ago544

reply all(2)I'll reply

  • 黄舟

    黄舟2017-04-18 10:53:00

    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);

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:53:00

    1. Correct

    2. Because class Integer implements Comparable<Integer>

    reply
    0
  • Cancelreply