创建compareTo到实现Comparable的泛型类

Jai*_*iro 19 java generics interface comparable

我有一个带有两个类型变量的Generic Class,它实现了java.lang.Comparable.

public class DoubleKey<K,J> implements Comparable<DoubleKey<K,J>>{

    private K key1;
    private J key2;

    public DoubleKey(K key1, J key2){
        this.key1 = key1;
        this.key2 = key2;
    } 

    public K getFirstKey(){
        return this.key1;
    }

    public J getSecondKey(){
        return this.key2;
    }

    // need for Comparable interface
    public int compareTo(DoubleKey<K,J> aThat){
        ...
    }

}

因为我用Comparable实现它,我需要编写compareTo()方法.因为K,J可以是任何类型,我在如何完全比较它时遇到问题.有没有办法能够在比较中捕获所有可能的类型(Primitive,Wrapper,Object)?谢谢您的帮助!

oli*_*ner 13

所以总结一下上面说的并将它拼凑成一个工作代码,这是:

    public class DoubleKey<K extends Comparable<K>, J extends Comparable<J>>
        implements Comparable<DoubleKey<K, J>> {

    private K key1;
    private J key2;

    public DoubleKey(K key1, J key2) {
        this.key1 = key1;
        this.key2 = key2;
    }

    public K getFirstKey() {
        return this.key1;
    }

    public J getSecondKey() {
        return this.key2;
    }

    public int compareTo(DoubleKey<K, J> that) {

        int cmp = this.getFirstKey().compareTo(that.getFirstKey());
        if (cmp == 0)
            cmp = this.getSecondKey().compareTo(that.getSecondKey());
        return cmp;
    }
}
Run Code Online (Sandbox Code Playgroud)


sjr*_*sjr 8

您想介绍一个可以使用KJ具有自然顺序的要求吗?在这种情况下,您可以DoubleKey像这样声明您的类:

class DoubleKey<K extends Comparable<K>, J extends Comparable<J>>
Run Code Online (Sandbox Code Playgroud)

然后,您可以根据需要定义DoubleKey compareTo.你可以这样做:

getFirstKey().compareTo(aThat.getFirstKey())
Run Code Online (Sandbox Code Playgroud)

但是,您无法将任何实例与K实例进行比较J.没有为这些类型定义排序.

如果这些类型不一定具有自然顺序(许多不具有),则可以将a Comparator<K>Comparator<J>as作为参数添加到您的构造函数中DoubleKey.已经可以用作示例的类是Google Guava的优秀Maps类(具体参见newTreeMap它们接受的类型的方法和界限).

  • `K扩展可比较<?super K>`会更好,因为它适当地处理Comparable类的子类 (2认同)