gpt4 book ai didi

java - 为实现 Comparable 的泛型类创建一个 compareTo

转载 作者:太空狗 更新时间:2023-10-29 22:33:50 26 4
gpt4 key购买 nike

我有一个带有两个类型变量的通用类,它实现了 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 可以是 ANY 类型,所以我在如何完全比较它们方面遇到了问题。有没有办法在比较中捕获所有可能的类型(原始、包装、对象)?感谢您的帮助!

最佳答案

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

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

关于java - 为实现 Comparable 的泛型类创建一个 compareTo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5013947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com