[英]Can you specify a generic type that subclasses another generic type _and_ a concrete interface?
[英]How can you bind the type of a generic interface to another generic interface?
我正在嘗試編寫一個具有多層界限的接口。 例如,考慮以下代碼:
// the bound type on U is unexpected and doesn't compile
public interface CollectionNumberWrapper<T extends Collection<U extends Number>> {
void setData(T data);
U sumOfAllNumbersInCollection()
};
public class NumberCollection implements List<AtomicInteger>{
///...implement...
};
public class StringCollection implements Collection<String>{
///...implement...
};
//This should be legal
public class NumberCollectionWrapper implements CollectionNumberWrapper<NumberCollection>{
@Override
void setData(NumberCollection data){
//...
};
@Override
AtomicInteger sumOfAllNumbersInCollection(){
//...
}
}
//This should not be legal, the type parameter should be out of bounds
public class StringCollectionWrapper implements CollectionNumberWrapper<StringCollection>{
}
是否可以在 Java 中使用這種特定的類型界限?
可以,但需要多做一些工作:你必須寫
public interface CollectionNumberWrapper<U extends Number, T extends Collection<U>> { ... }
...雖然對於這個特定的用例,我會完全省略T
並簡單地在任何地方使用Collection<U>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.