[英]Java TreeMap not sorted according to passed comparator
I have implemented a TreeMap that contains blueprints (to simplify it).我已经实现了一个包含蓝图的 TreeMap(为了简化它)。
private TreeMap<BuildingFloorKey, Blueprint> blueprints = new TreeMap<>((o1, o2) -> {
int value = o1.compareTo(o2);
return value;
});
To use building (in my case called complex) and floor as a tuple key, I wrote the following class:为了使用 building(在我的例子中称为 complex)和 floor 作为元组键,我编写了以下 class:
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);
}
}
I am working on an Android App and I want to click through the blueprints via buttons.我正在开发一个 Android 应用程序,我想通过按钮单击蓝图。 For that I make use of the methods TreeMap.lowerKey(otherKey) and TreeMap.higherKey(otherKey).
为此,我使用了 TreeMap.lowerKey(otherKey) 和 TreeMap.higherKey(otherKey) 方法。 Like so:
像这样:
@Override
public void onNextPlanClicked() {
nextFloorPlan = blueprints.higherKey(currentlyDisplayedPlan);
drawFloorPlan(nextFloorPlan);
}
As an example, I have a usecase where the set of blueprints is例如,我有一个用例,其中一组蓝图是
(format: complex|floor). (格式:复杂|楼层)。 Unfortunately, it is not sorted properly in the TreeMap (as you can see - the list above is sorted like the entries of the TreeMap in the debugger).
不幸的是,它在 TreeMap 中没有正确排序(如您所见 - 上面的列表与调试器中 TreeMap 的条目一样排序)。
I read something about TreeMap Sorting using case-sensitive Strings.我读了一些关于 TreeMap Sorting using case-sensitive Strings 的文章。 But I'm actually using integers.
但我实际上使用的是整数。 So I don't get why sorting and using lowerKey() and higherKey() not working properly.
所以我不明白为什么排序和使用 lowerKey() 和 highKey() 不能正常工作。 Did I mess up with the comparator?
我搞砸了比较器吗? Can someone help please?
有人可以帮忙吗?
I think your issues is a very simple one, your compareTo method should have an override.我认为您的问题非常简单,您的 compareTo 方法应该有一个覆盖。 You need to add implements Comparable to your BuildingFloorKey definition, which will then take your compareTo argument as a comparable that TreeMap can recognize.
您需要将实现 Comparable 添加到您的 BuildingFloorKey 定义中,然后它将您的 compareTo 参数作为 TreeMap 可以识别的可比较参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.