TreeSet 比较器 OR comparble.compareTo() 优先级
如果Java TreeSet设置了一个比较器来处理对象排序逻辑,但是对象(类)也实现了comparable并且在其上实现了有效的compareTo方法。
哪一个优先?比较器内的逻辑还是compareTo方法中的逻辑?
非常感谢。
If the Java TreeSet is set with a comparator to deal with the objects sorting logic But the objects ( class) also implements comparable and have valid compareTo method implemented on it.
Which one takes priority? The logic within the comparator or the logic in the compareTo method?
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
传入 TreeSet 构造函数的 Comparator 优先。这允许使用与对象的
compareTo
实现的不同的比较算法。如果不是这样,您将永远无法对 TreeSet 使用不同的比较算法。The Comparator passed-in to TreeSet's constructor takes priority. This allows for using a different comparison algorithm than is implemented by the object's
compareTo
. If it weren't for this, you'd never be able to use a different comparison algorithm with TreeSet.这已经说得很清楚 Javadocs(添加了重点):
This is spelt out pretty clearly in the Javadocs (emphasis added):