[英]how to implement Treemap with comparator?
我在此问题中遇到的错误已解决,并写在下面的“答案”部分。
问题是,TreeMap的以下定义引发了编译器错误,我想知道原因。
Comparator<Student> comparator=new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.roll<=o2.roll)
return -1;
else return 1;
}
};
TreeMap<Integer, Student> map=new TreeMap<>(comparator);
我不了解Treemap的此实现错误的原因。 谁能解释一下这里发生的事情吗?
compare()
需要处理三种情况:小于,大于和等于。 当它们相等时,您需要返回0
。
if (o1.roll == o2.roll) {
return 0;
}
else if (o1.roll < o2.roll) {
return -1;
}
else {
return 1;
}
Integer.compare(int x, int y)
可以为您完成所有这些操作:
public int compare(Student o1, Student o2) {
return Integer.compare(o1.roll, o2.roll);
}
在Java 8中,您可以在一行中创建整个比较器:
Map<Integer, Student> map = new TreeMap<>(Comparator.comparingInt(s -> s.roll));
TL; DR: TreeMap<Integer, Student>
比较器需要比较Integer
而不是Student
。
TreeMap<Integer, Student>
从整数(“键”)到学生对象(“ values”)的映射,并按整数对映射进行排序。 因此,构造函数不接受Comparator<Student>
作为参数。
根据TreeMap<K,V>
的文档,以比较器为参数的构造函数声明为
TreeMap(Comparator<? super K> comparator)
这意味着比较器必须在类型K
,键的类型或K
某些超类型上工作。 在您的情况下, K
为Integer
。
由于Integer
类已经定义了一种顺序,即所谓的自然顺序,因此我建议您根本不需要比较器:
TreeMap<Integer, Student> map = new TreeMap<>();
如果您想按学生的roll
号存储他们,只需像这样插入他们:
Student me = new Student();
map.put(me.roll, me);
副作用是地图按roll
排序。
PS John Kugelman回答中的信息也是正确的,比较器需要处理三种情况。 推荐使用Comparator.comparingInt(s -> s.roll)
或Comparator.comparingInt(Student::getRoll)
(如果该类具有这种吸气剂),不仅是为了简洁,而且还因为它不容易出错而被推荐使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.