在我的项目中,我有多个严格排序的类型,我需要它们全部支持范围操作-给定两个边界值,返回所有中间值的列表。
为了不重复我自己,我将创建一个类似于以下内容的“特征”,该特征将声明相应的原始操作并在顶部构建一个range方法。
public interface Navigable {
public Navigable previous() throws UnsupportedOperationException;
public boolean isFirst();
public Navigable next() throws UnsupportedOperationException;
public boolean isLast();
public boolean precedes(Navigable other);
public default List<Navigable> range(Navigable to) {
Navigable from = this;
boolean invert = to.precedes(from);
if (invert) {
Navigable tmp = from;
from = to;
to = tmp;
}
List<Navigable> result = new LinkedList<>();
while (from.precedes(to)) {
result.add(from);
from = from.next();
}
result.add(to);
if (invert) {
reverse(result);
}
return result;
}
}
但是,使用这样的接口,我需要实现以下操作:
public class Item implements Navigable {
...
@Override
public boolean precedes(Navigable other) {
...
}
...
}
当然,这是不正确的。我需要的是以下内容。
public class Item implements Navigable {
...
@Override
public boolean precedes(Item other) {
...
}
...
}
希望我要实现的目标是明确的。正确的方法是什么?
您必须使接口通用,并稍微改变abstract
方法。
例如:
public interface Navigable<T extends Navigable> {
...
public boolean preceeds(T other);
..
}
然后,在实现接口时,您将能够做到(没有任何编译错误):
public class Item implements Navigable<Item> {
...
@Override
public boolean preceeds(Item other) {
...
}
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句