Heim  >  Fragen und Antworten  >  Hauptteil

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

高洛峰高洛峰2743 Tage vor545

Antworte allen(2)Ich werde antworten

  • 黄舟

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

    截图红字的理解基本没错但不完全,正如 @jokester 说的,你没把代码贴全,注意第561行 else 前面的部分。实际上,TreeMap<T>或TreeSet<T>,排序依据有两种情况:

    1. 创建时带了Comparator<? super T>,那么排序依据这个Comparator;

    2. 创建时不带Comparator<? super T>,那么要求T必须实现Comparable。

    所以看TreeSet<Person>的情况,如果创建时带了Comparator<Person>,那么Person完全可以不实现Comparable。

    另外,Integer本身实现了Comparable类型,所有基本类型的封装对象(还有Long、Double、Boolean等),以及String都,都实现了Comparable,所以当然可以强转。

    最后留一个问题给大家,TreeMap创建时带Comparator的话,为什么要指定类型Comparator<? super K>,而不是Comparator<K>Comparator<? extends K>?参阅TreeMap的一个构造函数:

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

    Antwort
    0
  • 迷茫

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

    1. 正確

    2. 因爲 class Integer implements Comparable<Integer>

    Antwort
    0
  • StornierenAntwort