gpt4 book ai didi

java generics - Comparable 类型中的方法compareTo(capture#1-of ?) 不适用于参数

转载 作者:行者123 更新时间:2023-12-01 16:39:13 26 4
gpt4 key购买 nike

所以我想这样做:

public interface IFieldObject {
public Comparable get();
}

public interface IFieldCondition {
public boolean apply(IFieldObject field, Comparable compare);
}

public class EqualTo implements IFieldCondition {
public boolean apply(IFieldObject field, Comparable compare) {
return (field.get().compareTo(compare) == 0);
}
}

但是 Eclipse 给了我警告:

Type safety: The method compareTo(Object) belongs to the raw type Comparable. References to generic type Comparable should be parameterized

所以我把它变成了:

public interface IFieldObject {
public Comparable<?> get();
}

public interface IFieldCondition {
public boolean apply(IFieldObject field, Comparable<?> compare);
}

public class EqualTo implements IFieldCondition {
public boolean apply(IFieldObject field, Comparable<?> compare) {
return (field.get().compareTo(compare) == 0);
}
}

由于以下原因无法编译:

The method compareTo(capture#1-of ?) in the type Comparable is not applicable for the arguments (Comparable)

正确的做法是什么?(遵循惯用的 Java >= 1.6,没有警告)

最佳答案

目前您无法保证 field.get() 返回的类型确实与该方法指定的类型具有可比性。理想情况下,使整个事情通用,例如:

public interface IFieldObject<T extends Comparable<T>> {
public T get();
}

public interface IFieldCondition<T> {
public boolean apply(IFieldObject<T> field, Comparable<T> compare);
}

public class EqualTo<T> implements IFieldCondition<T> {
public boolean apply(IFieldObject<T> field, Comparable<T> compare) {
return (field.get().compareTo(compare) == 0);
}
}

毫无疑问,您可以使用额外的捕获来使其更加通用,但这就是起点。

关于java generics - Comparable<capture#1-of ?> 类型中的方法compareTo(capture#1-of ?) 不适用于参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5872251/

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