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

只谈情不闲聊 提交于 2020-01-17 01:22:09

问题


So I want to do this:

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

but Eclipse gives me warnings:

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

So I turned this into:

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

which does not compile because of:

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

What's the right way to do that ? (without warnings following idiomatic Java >= 1.6)


回答1:


How about this?

public interface IFieldObject {
    public<T> Comparable<T> 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);       
    }
}



回答2:


Currently you've no guarantee that the type returned by field.get() is really comparable with the type specified by the method. Ideally, make the whole thing generic, e.g.:

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

You could no doubt make this more general using extra captures, but that's the starting point.



来源:https://stackoverflow.com/questions/5872251/java-generics-the-method-comparetocapture1-of-in-the-type-comparablecapt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!