gpt4 book ai didi

java - Java 中的通用特征

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:55:00 25 4
gpt4 key购买 nike

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

为了不重复我自己,我想我会创建一个像下面这样的“特征”,它会声明相应的原始操作并在顶部构建一个范围方法。

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

但是,有了这样的接口(interface),我需要实现这样的操作:

public class Item implements Navigable {
...
@Override
public boolean precedes(Navigable other) {
...
}
...
}

当然,这是不正确的。我需要的是以下内容。

public class Item implements Navigable {
...
@Override
public boolean precedes(Item other) {
...
}
...
}

希望我要实现的目标是明确的。执行此操作的正确方法是什么?

最佳答案

您必须使您的界面通用并稍微更改抽象方法。

例如:

public interface Navigable<T extends Navigable> {
...
public boolean preceeds(T other);
..
}

然后,当您实现该接口(interface)时,您将能够(没有任何编译错误):

public class Item implements Navigable<Item> {
...
@Override
public boolean preceeds(Item other) {
...
}
...
}

关于java - Java 中的通用特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349385/

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