[英]TreeMap Comparator not giving the order expected?
I am attempting to create a TreeMap
with the following Format: 我正在尝试使用以下格式创建
TreeMap
:
TreeMap<Kenel, List<Dog>> treeMapOfKennelsAndDogs;
Each entry is a Kennel
object with an attached list of Dogs
. 每个条目都是一个
Kennel
对象,附带一个Dogs
列表。 I want to compare each Kennel by the oldest Dog in each and order accordingly. 我想比较每个犬舍中最老的狗,并相应地进行排序。
However the order of the treeMap
is not what I am expecting, it seems that when a Kennel has a Dog List of size 1 in the list then the ordering is incorrect. 然而,
treeMap
的顺序并不是我所期望的,似乎当一个狗窝在列表中有一个大小为1的狗列表时,顺序是不正确的。
Below is my code to find the oldest Dog related to each Kennel, and also my comparator logic. 下面是我的代码,找到与每个狗窝相关的最老的狗,以及我的比较器逻辑。
@Entity
@Table(name = "KENNEL")
public class Kennel {
//other fields
@OneToMany(cascade = CascadeType.MERGE, orphanRemoval = true)
@JoinColumn(name = "KENNEL_ID", referencedColumnName = "ID", updatable = true, insertable = true)
private List<Dog> dogList;
public DateTime getOldestDogInList() {
if (dogList.size() == 0) {
return null; }
Dog dog= dogList.get(0);
for (int i = 1; i < dogList.size(); i++) {
dog d = dogList.get(i);
if (d.getCreated().isBefore(dog.getCreated())) {
dog = d;
}
}
return dog.getCreated();
}
Comparator logic in service class: 服务类中的比较器逻辑:
Comparator<Kennel> oldestDog = new Comparator<Kennel>() {
@Override
public int compare(Kennel k1, Kennel k2) {
int result = k1.getOldestDogInList().compareTo(k2.getOldestDogInList());
return result;
}
};
TreeMap<Kennel, List<Dog>> treeMapOfKennelsAndDogs = new TreeMap<>(oldestDog);
Is there an error in code that would cause the incorrect ordering in the TreeMap? 代码中是否存在错误导致TreeMap中的错误排序?
Comparator logic in service class:
服务类中的比较器逻辑:
TreeSet don't know about your service classes. TreeSet不了解您的服务类。 It knows only about Generic type inside.
它只知道里面的Generic类型。
1st sollution: 第一次溶解:
Comparator logic should be in a class that will be sorted in TreeSet
. 比较器逻辑应该在将在
TreeSet
排序的类中。 You should implement Comparator
and ovverade compare
method in Kennel
class. 您应该在
Kennel
类中实现Comparator
和ovverade compare
方法。
2nd sollution: 第二次溶解:
Set Comparator
when create TreeMap
. 创建
TreeMap
时设置Comparator
。
TreeMap<Kenel, List<Dog>> treemap = new TreeMap<Kenel, List<Dog>>(new Comparator<Kenel>() {
public int compare(Kennel k1, Kennel k2) {
int result = k1.getOldestDogInList().compareTo(k2.getOldestDogInList());
return result;
}
});
Related question: What is the difference between compare() and compareTo()? 相关问题: compare()和compareTo()有什么区别?
Map<K, V>
keys should not depend on V
class. Map<K, V>
键的逻辑不应该依赖于V
类。 Map
? Map
插入后修改键实例吗? If yes - it is a problem.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.