为什么在这个通用接口中需要不安全的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 –