java 比较接口_Java中的可比较和比较器接口

让我们先看一下界面设计.

public interface Comparable {

public int compareTo(T o);

}

我们必须说这是很典型的.因此,如果我们的课程需要实现它,我们就这样做.

pubilc class ICanComparteWithMyself implements Comparable {

public int compareTo(ICanComparteWithMyselfo)

//code for compration

}

当我们看到通用参数类型时,确定我们将要操作的内容,因此对于泛型,我们以相同的方式操作

public class ICanCompareMyGeneric implements Comparable {

public int compareTo(T o)

//code for compration

}

}

在你的情况下,我们希望它确保泛型参数实现是自己的Comparable,为此我们需要这样做

public class MyGenericCanCompareToItself> {

}

我们可以看到,这是很常见的使用方法.预期(或不是)的限制是我们可以处理为其自身类型实现Comparable的类.如果我们有

public class ICanCompareStrings implements Comparable {

public int compareTo(String o)

//code for compration

}

}

因此,对于类MyGenericCanCompareToItself作为泛型参数,我们可以使用类public MyGenericCanCompareToItself但不能使用ICanCompareStrings.

编辑:

因此,当我们涵盖基础知识时,我们可以解决您的问题

您的班级描述如下所示

公共类对< T1扩展Comparable,T2扩展Comparable>

这没有太多的感觉,因为与相同.

这个描述说:

I am a Pair class, that work with two generic parameters, that can use comparison over something that I do not know.

使用这段代码,你不能在通用参数不知道之前进展,然后在那里操作,最终得到这样的东西.

first.getKey.compareTo(NULL);

这就是为什么你编写的代码在你尝试强制转换时不能编译,期望的类型为null.

要更改它,您需要确定您的通用参数应具有可比性的类型.

例如,可以在itselft上进行比较

公共类对< T1扩展Comparable< T1>,T2扩展Comparable< T2>>

这个描述说:

I am a Pair class that works with two parameters, that each of them can be compared with itself.

这就是你可能正在寻找的东西,另外它们可以在一些可以超级T1或T2的东西上进行比较

公共类对< T1扩展Comparable,T2扩展可比较

这个描述说:

I am a Pair class that works with two parameters, that each of them can be compared with classes that deliver from them.

我希望这可以帮助你使用泛型;-).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值