创建compareTo到实现Comparable的通用类
我有一个带有两个类型变量的Generic Class,它实现了java.lang.Comparable。
公共类DoubleKey 实现Comparable <DoubleKey > { 私人K key1; 私人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; } //需要Comparable接口 public int compareTo(DoubleKey aThat){ ... } }
因为我用Comparable实现它,我需要编写compareTo()方法。 因为K,J可以是任何类型,我在如何完全比较它时遇到问题。 有没有办法能够在比较中捕获所有可能的类型(Primitive,Wrapper,Object)? 谢谢您的帮助!
所以总结一下上面说的并将它拼凑成一个工作代码,这是:
public class DoubleKey, J extends Comparable> implements Comparable> { 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 that) { int cmp = this.getFirstKey().compareTo(that.getFirstKey()); if (cmp == 0) cmp = this.getSecondKey().compareTo(that.getSecondKey()); return cmp; } }
您是否想要介绍K
和J
具有可以使用的自然顺序的要求? 在这种情况下,您可以像这样声明您的类DoubleKey
:
class DoubleKey, J extends Comparable>
然后,您可以根据需要定义DoubleKey的compareTo
。 你可以这样做:
getFirstKey().compareTo(aThat.getFirstKey())
但是,您无法将K
任何实例与J
的实例进行比较。 没有为这些类型定义排序。
如果这些类型不一定具有自然顺序(许多不具有),则可以将Comparator
和Comparator
作为DoubleKey
构造函数的参数。 已经可以用作示例的类是Google Guava的优秀Maps类(具体参见newTreeMap
方法及其接受的类型的界限)。
公共类DoubleKey < K实现了Comparable, J实现了Comparable > 实现Comparable > { public int compareTo(DoubleKey that){ int cmp = this.key1.compareTo(that.key1); if(cmp == 0)cmp = this.key2.compareTo(that.key2); 返回cmp; } }
当 DoubleKey
小于,大于或等于此时,您必须定义规则。 这就是比较的结果。 也许,这是我的实际猜测,与DoubleKey
实例进行比较没有多大意义。
如果您没有真正关心如何订购,只需要实施任何订购,请尝试以下方法:
public int compareTo(DoubleKey that){ // real codes needs checks for null values! return (this.key1.toString() + this.key2.toString()).compareTo(that.key1.toString() + that.key2.toString()); }
第一种方式:使用hashCodes,比如
public int compareTo(DoubleKey aThat){ getFirstKey().hashCode() + getSecondKey().hashCode() - aThat.getFirstKey().hashCode() + aThat.getSecondKey().hashCode(); }
(你应该多考虑一下公式)
第二种方法:将比较器添加到构造函数
public DoubleKey(K key1, J key2, Comparator cmp){
通常情况下,存在一个可以解决您的问题的库: Apache Commons lang3 。 我经常使用Pair