爲什麼在這個通用接口中需要不安全的cast (T)
?如果T
媲美本身,即實現ExtendedComparable<super of T>
這意味着還ExtendedComparable<T>
,那麼爲什麼類型擦除需要ExtendedComparable<T>
定投至T?如何避免Java泛型擴展Comparable接口中未經檢查的強制轉換?
/* @param <T> T must be comparable to itself or any of its superclass
* (comparables are consumers, thus acc. to the PECS principle
* = producer-extends,consumer-super we use the bounded wildcard type "super")
*/
public interface ExtendedComparable<T extends ExtendedComparable<? super T>> {
Comparator<? super T> getComparator();
default boolean greaterThen(T toCompare) {
return getComparator().compare((T) this, toCompare) > 0;
}
}
這篇文章可以爲您的幫助:https://stackoverflow.com/a/25783345/4867374 –