gpt4 book ai didi

java - 如何使用 Comparable

转载 作者:行者123 更新时间:2023-11-29 09:55:50 24 4
gpt4 key购买 nike

我有以下接口(interface)

public interface Identifiable {

public Comparable<?> getIdentifier();

}

还有一个实现类

public class Agreement implements Identifiable {

private Long id;

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

编辑:请注意,可能还有其他具有不同类型标识符的实现。
是的,现在我想比较可比对象:

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

但是 compareTo 给我以下编译器错误:

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

这个接口(interface)应该如何与泛型一起使用?

最佳答案

Comparable<T>旨在用作通用参数的上限:

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

这强制返回类型为 T ,不仅仅是可以与 T 相提并论的东西.


您的代码本质上是不安全的。
要理解原因,请考虑以下代码:

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)

关于java - 如何使用 Comparable<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12074557/

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