[英]Java Collection compare generic class that extends interface that extends comparable
我有這個界面
public interface IDataPoint<T> extends Comparable<T> {
public T getValue();
}
還有這個實現
public class IntegerDataPoint implements IDataPoint<Integer> {
// ... some code omitted for this example
public int compareTo(Integer another) {
// ... some code
}
}
還有另一堂課
public class HeatMap<X extends IDataPoint<?> {
private List<X> xPoints;
}
現在,我想在xPoints
列表上使用Collections.max(和類似的東西),但這不起作用,可能是因為我弄亂了所有的泛型。
有什么建議可以解決這個問題(沒有Comparator
)?
Collections.max(xPoints);
給我這個錯誤:
Bound mismatch: The generic method max(Collection<? extends T>) of type Collections is not applicable for the arguments (List<X>). The inferred type X is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>
問題在於Collections.max(Collection<? extends T>)
希望T與自己具有可比性, 而不是其他類型。
在您的情況下, IntegerDataPoint
與Integer
相當,但與IntegerDataPoint
不IntegerDataPoint
您不能輕松地解決此問題,因為不允許IntegerDataPoint
同時實現Comparable<Integer>
和Comparable<IntegerDataPoint>
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.