简体   繁体   English

Java Comparable - 自定义 compareTo 结果

[英]Java Comparable - custom compareTo consequences

I have a question regarding a specific overriding of compareTo.我有一个关于 compareTo 的特定覆盖的问题。

class Sjavac {
static class A implements Comparable<A> {
    @Override
    public int compareTo(A a) {
        return 1;
    }

    @Override
    public String toString() {
        return this.getClass().toString();
    }
}

static class B extends A {
    @Override
    public int compareTo(A a) {
        return 1;
    }
}

public static void main(String[] args) {
    List<A> list = new ArrayList<>();
    list.add(new A());
    list.add(new B());
    Collections.sort(list);
    for(A a : list){
        System.out.println(a);
    }
}
}

The result I get is that first A's string is printed, and then B's.我得到的结果是首先打印 A 的字符串,然后是 B 的。

My question is, why is this the result?我的问题是,为什么会是这样的结果? What exactly happends in this case?在这种情况下究竟发生了什么? When A is compared to B, it is considered bigger, and when B is compared to A it is considered bigger.当 A 与 B 相比时,它被认为更大,而当 B 与 A 相比时,它被认为更大。 Than what determines that order?是什么决定了那个顺序?

Thanks谢谢

In this case the result is undefined because you can't sort a list where the elements are changing.在这种情况下,结果是未定义的,因为您无法对元素发生变化的列表进行排序。 So, if you want to know why this is the result you have to check how the sorting algorithm works.所以,如果你想知道为什么会出现这个结果,你必须检查排序算法是如何工作的。

You are comparing B to A and return B should come after A (in B's compare to method).您正在将 B 与 A 进行比较,并且返回 B 应该在 A 之后(在 B 的比较方法中)。 Also, you are comparing A with A and saying the first one should come after the second one (in A's compare to method).此外,您将 A 与 A 进行比较,并说第一个应该在第二个之后(在 A 的比较方法中)。 Then, you have a list with A object and B object.然后,您有一个包含 A 对象和 B 对象的列表。 Sorting this, A is compared to B, B is greater (comes later), and that is returned.对此进行排序,将 A 与 B 进行比较,B 更大(稍后出现),然后返回。

The trick happened here, why do Collections.sort method choose B's implementation of compareTo?诀窍在这里发生了,为什么 Collections.sort 方法选择 B 的 compareTo 实现? Because it's late binding!因为是后期绑定! It's inheritance.是传承。 Check this implementation, with console printing...检查此实现,使用控制台打印...

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Sjavac {
static class A implements Comparable<A> {
    @Override
    public int compareTo(A a) {
        System.out.println("A");
        return 1;
    }

    @Override
    public String toString() {
        return this.getClass().toString();
    }
}

static class B extends A {
    @Override
    public int compareTo(A a) {
        System.out.println("Here");
        return 1;
    }
}

public static void main(String[] args) {
    List<A> list = new ArrayList<>();
    list.add(new A());
    list.add(new B());
    Collections.sort(list);
    for(A a : list){
        System.out.println(a);
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM