我正在嘗試使用自定義比較器實現NavigableMap,該比較基於值而不是按鍵進行比較。我非常瞭解java和一般編碼,所以如果我的術語是inccorect或代碼可怕,請原諒我!我試圖尋找類似的問題,試圖複製解決方案,但我仍然recieving以下錯誤,當我嘗試編譯:NavigableMap - 基於值進行比較
java: no suitable constructor found for TreeMap(OrderLineSegments)
constructor java.util.TreeMap.TreeMap(java.util.Comparator<? super java.lang.Float>) is not applicable
(argument mismatch; OrderLineSegments cannot be converted to java.util.Comparator<? super java.lang.Float>)
constructor java.util.TreeMap.TreeMap(java.util.Map<? extends java.lang.Float,? extends java.lang.Float[]>) is not applicable
(argument mismatch; OrderLineSegments cannot be converted to java.util.Map<? extends java.lang.Float,? extends java.lang.Float[]>)
constructor java.util.TreeMap.TreeMap(java.util.SortedMap<java.lang.Float,? extends java.lang.Float[]>) is not applicable
(argument mismatch; OrderLineSegments cannot be converted to java.util.SortedMap<java.lang.Float,? extends java.lang.Float[]>)
我想實現以下內容,其中浮法[]爲4個float數組[ x1,y1,x2,y2]表示線段。
NavigableMap<Float, Float[]> segmentBST = new TreeMap<Float, Float[]>(new OrderLineSegments());
class OrderLineSegments implements Comparator<Map.Entry<Float, Float[]>> {
public int compare(Map.Entry<Float, Float[]> a, Map.Entry<Float, Float[]> b) {
float ypos;
if (a.getValue()[1] < a.getValue()[1]) {
ypos = a.getValue()[1];
} else {
ypos = b.getValue()[1];
}
float ratioA = (a.getValue()[1] - ypos)/(ypos - a.getValue()[3]);
float ratioB = (b.getValue()[1] - ypos)/(ypos - b.getValue()[3]);
float posA = Math.abs(a.getValue()[0] - a.getValue()[2]) * ratioA + a.getValue()[0];
float posB = Math.abs(b.getValue()[0] - b.getValue()[2]) * ratioB + b.getValue()[0];
if (posA < posB) return 1;
if (posA > posB) return -1;
return 0;
}
我甚至不確定這是否是最好的方法來做到這一點,或者如果這是甚至可能,所以任何援助非常感謝。
「比較器」用於比較*鍵*,因此'OrderLineSegments'需要實現'比較器'。因此,當您嘗試比較Map.Entry時出錯。 –
Kayaman
錯誤似乎很正常,因爲文檔說:'TreeMap的構造函數需要比較器 super K>',並且您提供了一個'比較器>'它不能像,不能反轉鍵和值嗎?如果您沒有相同的值,則可能會更改 –
azro
您正在違反NavigableMap的合同。爲什麼不在這種情況下使用排序列表? – daniu