简体   繁体   English

Java可比和接口

[英]Java Comparable and Interface

Lets Say you have ClassA, ClassB, ClassC, and interfaceA. 假设您有ClassA,ClassB,ClassC和interfaceA。

ClassA and ClassB implements interfaceA, The classC contains a List< interface > ClassA和ClassB实现interfaceA,classC包含List <interface>

Now lets say we add some values from ClassA and ClassB into ClassC List 现在假设我们将ClassA和ClassB中的一些值添加到ClassC列表中

What happens if ClassA implement different comparable method CompareTo than ClassB, and we call Collection.sort(list< interface >) 如果ClassA实现与ClassB不同的可比较方法CompareTo,我们将调用Collection.sort(list <interface>),会发生什么情况

which CompareTo will be applied to sort the list ? 哪个CompareTo将应用于对列表进行排序? or we must have the same CompareTo method in every Class that implement interfaceA 否则我们在实现interfaceA的每个类中必须具有相同的CompareTo方法

The Comparable interface is not a best approach. 可比接口不是最佳方法。 I would recommend using a Comparator passed into the Collection sort method. 我建议使用传递给Collection排序方法的Comparator。

I think you are not able to run such code. 我认为您无法运行此类代码。 Imagine you have an abstract class: 假设您有一个抽象类:

public abstract class Number<T extends Number<T>> implements Comparable<T> {}

and two classes which extend it: 和两个扩展它的类:

public class One extends Number<One> {
    @Override
    public int compareTo(One o) {
        return -1;
    }
}

public class Two extends Number<Two> {
    @Override
    public int compareTo(Two o) {
        return 0;
    }
}

Then execution of the following snippet: 然后执行以下代码段:

List<Number> list = new ArrayList<>();
list.add(new One());
list.add(new Two());
Collections.sort((List<Number>) list);

will throw a ClassCastException 将抛出ClassCastException

 Exception in thread "main" java.lang.ClassCastException: comparable.One cannot be cast to comparable.Two 

In general your idea breaks the contract of the compareTo method (See Joshua Bloch Effective Java , Item 12): 通常,您的想法违反了compareTo方法的约定(请参见Joshua Bloch Effective Java ,项目12):

  • The implementor must ensure sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y . 实现者必须确保所有x和y的sgn(x.compareTo(y))== -sgn(y.compareTo(x))。
  • The implementor must also ensure that the relation is transitive: (x.com- pareTo(y) > 0 && y.compareTo(z) > 0) implies x.compareTo(z) > 0. 实现者还必须确保该关系是可传递的:(x.comparToTo(y)> 0 && y.compareTo(z)> 0)意味着x.compareTo(z)> 0。
  • Finally, the implementor must ensure that x.compareTo(y) == 0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)) , for all z . 最后,实现者必须确保对于所有z,x.compareTo(y)== 0意味着sgn(x.compareTo(z))== sgn(y.compareTo(z))。
  • It is strongly recommended, but not strictly required, that (x.compareTo(y) == 0) == (x.equals(y)). 强烈建议(但并非严格要求)(x.compareTo(y)== 0)==(x.equals(y))。

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

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