创建一个compareTo实现可比较的通用类 [英] Create a compareTo to a Generic Class that Implements Comparable

查看:123
本文介绍了创建一个compareTo实现可比较的通用类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有两个类型变量的泛型类,它们实现java.lang.Comparable。

 
public class DoubleKey< K,J> ;实现可比< DoubleKey< K,J>> {

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

//需要比较接口
public int compareTo(DoubleKey< K,J> aThat){
...
}





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

解决方案

所以总结一下上面的内容, p>

  public class DoubleKey< K extends Comparable< K>,J extends Comparable< J>> 
实现了Comparable< DoubleKey< K,J>> {

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

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


I have a Generic Class with two type variables, which implements 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){
        ...
    }

}

Becuase i implemeted it with Comparable, I need to write the compareTo() method. Because K, J can be of ANY type, I'm having problems on how to compare them completely. Is there a way to be able to catch all possible types (Primitive, Wrapper, Object) in the comparison? Thanks for the help!

解决方案

so to summarize the said above and to puzzle it together into a working code this is:

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

这篇关于创建一个compareTo实现可比较的通用类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆