Java 中的通用特征

A generic trait in Java

在我的项目中,我有多个严格排序的类型,我需要它们都支持范围操作 - 给定两个边界值,return 所有中间值的列表。

为了不再重复,我想创建一个如下所示的 "trait",它将声明相应的原始操作并在顶部构建一个范围方法。

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) {
        ...
    }
    ...
}