如何使用Comparable< T>? [英] How to use Comparable<T>?

查看:96
本文介绍了如何使用Comparable< T>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下接口

  public interface Identifiable {

public可比较<?>则getIdentifier();


$ / code>

而实现类

  public class Agreement implements Identifiable {

private Long id;

公众可比< Long> getIdentifier(){
return id;




$ b编辑:请注意,可能有其他实现与不同
现在我想,是的,比较可比较的数据:一个;
//协议b; (b.getIdentifier()){
...
$ b $

但是 compareTo 给了我下面的编译错误:

Comparable< Long>类型中的compareTo(Long)方法不适用于参数(Comparable< Long>)



这个接口是否应该与泛型一起使用?

解决方案

Comparable< T> 意味着用作泛型参数的上界:

  public interface可识别的< T扩展Comparable< T> > {
public T getIdentifier();
}

公共类协议实现可识别的< Long> {

private final Long id;

public Long getIdentifier(){
return id;
}
}

这强制返回类型为 T ,而不仅仅是t可以比作一个 T






你的代码是本质上是不安全的。

要理解为什么,请考虑以下代码:

  class Funny implements Comparable< Long> {...} 
类Funnier实现可识别{
public Comparable< Long> getIdentifier(){
return new Funny();
}
}

可识别< Funny>有趣;
funnier.getIdentifier()。compareTo(funnier.getIdentifier());
//你只是想通过一个Funny来compareTo(Long)


I have the following interface

public interface Identifiable {

    public Comparable<?> getIdentifier();

}

And an implementing class

public class Agreement implements Identifiable {

    private Long id;

    public Comparable<Long> getIdentifier() {
        return id;
    }
}

EDIT: Note that there may be other implementations with different types of identifiers.
Now I would like to, yes, compare the comparables:

// Agreement a;
// Agreement b;
...
if (a.getIdentifier().compareTo(b.getIdentifier()) {
...

But the compareTo gives me the following compiler error:

The method compareTo(Long) in the type Comparable<Long> is not applicable for the arguments (Comparable<Long>)

How is this interface supposed to be used with Generics?

解决方案

Comparable<T> is meant to be used as an upper bound for a generic parameter:

public interface Identifiable<T extends Comparable<T>> {    
    public T getIdentifier();
}

public class Agreement implements Identifiable<Long> {

    private final Long id;

    public Long getIdentifier() {
        return id;
    }
}

This forces the return type to be a T, not just something that can be compared to a T.


Your code is inherently unsafe.
To understand why, consider the following code:

class Funny implements Comparable<Long> { ... }
class Funnier implements Identifiable {
    public Comparable<Long> getIdentifier() {
        return new Funny();
    }
}

Identifiable<Funny> funnier;
funnier.getIdentifier().compareTo(funnier.getIdentifier());
// You just tried to pass a Funny to compareTo(Long)

这篇关于如何使用Comparable&lt; T&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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