Java TreeMap未根据传递的比较器进行排序



我实现了一个包含蓝图的TreeMap(以简化它(。

private TreeMap<BuildingFloorKey, Blueprint> blueprints = new TreeMap<>((o1, o2) -> {
int value = o1.compareTo(o2);
return value;
});

为了使用building(在我的例子中称为complex(和floor作为元组键,我编写了以下类:

public static class BuildingFloorKey {
private Complex mComplex;
private int mFloor;
public BuildingFloorKey(Complex complex, int floor){
mComplex = complex;
mFloor = floor;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof BuildingFloorKey)) return false;
BuildingFloorKey that = (BuildingFloorKey) other;
return mFloor == that.mFloor && mComplex.equals(that.mComplex);
}
@Override
public int hashCode() {
return Arrays.hashCode(new Object[]{mComplex, mFloor});
}
public int compareTo(BuildingFloorKey otherKey){
if(this.equals(otherKey)) return 0;
//same complex -> compare floors
else if (this.getComplex().equals(otherKey.getComplex())){
return otherKey.getFloorInt() - this.getFloorInt();
}
//different complexes (incl. some modification for special cases)
else return -(Math.abs(otherKey.mFloor + 2) + 100);
}
}

我正在开发一款安卓应用程序,我想通过按钮点击蓝图。为此,我使用了TreeMap.lowerKey(otherKey(和TreeMap.higherKey(otherKey(方法

@Override
public void onNextPlanClicked() {
nextFloorPlan = blueprints.higherKey(currentlyDisplayedPlan);
drawFloorPlan(nextFloorPlan);
}

举个例子,我有一个用例,其中蓝图集是

  • 04 | 02
  • 03年3月
  • 04 |-1
  • 03 | 00

(格式:complex | floor(。不幸的是,它在TreeMap中没有正确排序(正如您所看到的,上面的列表的排序与调试器中TreeMap的条目类似(。

我读过一些关于使用区分大小写的字符串进行TreeMap排序的文章。但我实际使用的是整数。所以我不明白为什么排序和使用lowerKey((和higherKey(((不能正常工作。我把比较器搞砸了吗?有人能帮忙吗?

我认为您的问题非常简单,您的compareTo方法应该有一个重写。您需要将实现Comparable添加到您的BuildingFloorKey定义中,然后它将把compareTo参数作为TreeMap可以识别的可比较参数。

最新更新