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)
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, eg:
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.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.