java中如何实现比较器?
Stop(Id, Name)
是一个 java 类,我想将这些停止对象存储在 java.util.Set
中,并且这些对象应根据 < Stop
的 code>Id。 这是我的比较器
public class StopsComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Stop stop1 = (Stop)o1;
Stop stop2 = (Stop)o2;
return stop1.getStopId().compareTo(stop2.getStopId());
}
}
private Set<Stop> stops = new TreeSet<Stop>(new StopsComparator());
,但它没有给出正确的结果?
Stop(Id, Name)
is a java class, and i want to store these stop objects in a java.util.Set
and those objects should be sorted according to the Id
of Stop
.
this is my comparator
public class StopsComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
Stop stop1 = (Stop)o1;
Stop stop2 = (Stop)o2;
return stop1.getStopId().compareTo(stop2.getStopId());
}
}
private Set<Stop> stops = new TreeSet<Stop>(new StopsComparator());
but its not giving correct result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Stop 是否实现了与比较器在同一字段上工作的 equals 方法?如果不这样做,就会导致问题。您可能还希望切换到让您的对象实现 Comparable (尽管这不能解决您所看到的问题)。
一旦实现了 equals() 方法,您还应该实现适用于同一字段的 hashCode() 方法。
Findbugs 可能会告诉你这些事情。它非常有用。
Does Stop implement an equals method that works on the same field as your comparator? If not then that will lead to problems. You also might want to switch to have your object implement Comparable (although that wouldn't fix the problem you're seeing).
Once you implement an
equals()
method, then you should also implement ahashCode()
method that works on the same field.Findbugs would have probably told you these things. Its extremely useful.
以下代码对我有用 -
印刷品 -
Ofc 您需要实现
equals
和hashcode
以便类在每个Set
实现中表现一致,但对于TreeSet
这应该按原样工作,因为TreeSet
在执行add
、remove
时依赖于compareTo
方法或包含
操作(而不是像HashSet
那样的equals
)。The following code works for me -
prints -
Ofc you need to implement
equals
andhashcode
so that class behaves consistently in eachSet
implementation, but forTreeSet
this should work as is sinceTreeSet
relies oncompareTo
method while performingadd
,remove
orcontains
operations (instead ofequals
likeHashSet
).这是来自
Comparator
文档:我建议尝试实现
equals
和hashCode
。This is from the
Comparator
docs:I would recommend to try implementing
equals
andhashCode
.