java 比较不同的选项
我已经实现了compareTo,允许我根据某些标准比较我的班级,并且工作正常。
但是,在某些时候,我想比较一件事上的类,而在代码中的另一点上,我想根据另一件事比较类。
是否可以有两种不同的compareTo 实现,并在某个时刻使用一个,在另一个时刻使用一个?
I have implemented compareTo to allow me to compare my class' based on some criteria and it is working fine.
However, at some point I want to compare the class' on one thing and at another point in the code I want to compare the class based on another thing.
Is it possible to have two different implementations of compareTo and using one at some point and one at another?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,执行此操作的机制是实现一个或多个 比较器并根据需要使用适当的比较器。
In general the mechanism to do this is to implement one or more Comparators and use the appropriate one as needed.
由于您的类是“可比较的”,您可以使用compareTo,但是您不能创建该函数的多个实现以在同一类的不同点使用(您有一个要重写的函数,并且您可以'不要这样做两次)。
但是,您可以查看比较器接口< /a>;该接口的实现可以让您为您的对象实现和使用不同的compareTo。
Since your Class is "Comparable" you can use the compareTo, you can't - however - create more then one implementation of that function to be used at different points in the same Class (you have one function to override, and you can't do that twice).
You can, however, take a look at the Comparator Interface; and implementation of that interface can allow you to implement and use a different compareTo for your object.
我们通过为我们的类编写一个实用程序比较器来实现类似的目标 - 像这样:
然后我们可以像这样使用它:
We achieved something similar by writing a utility comparator for our class - something like this:
We then can use it like this: