![](/img/trans.png)
[英]Re-using Java generic collections in Scala without trait Object
[英]A generic trait in Java
在我的項目中,我有多個嚴格排序的類型,我需要它們全部支持范圍操作 - 給定兩個邊界值,返回所有中間值的列表。
為了不重復自己,我會創建一個像下面這樣的“特征”,它將聲明相應的基本操作並在頂部構建一個范圍方法。
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) {
...
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.