如何使 Groovy 数组具有可比性?
尝试这样:
ArrayList.metaClass.compareTo = {arg -> this?.size() <=> arg?.size() }
[1]<=>[2]
它不起作用。
仍然出现异常 groovy.lang.GroovyRuntimeException: Cannot Compare java.util.ArrayList with value '[1]' and java.util.ArrayList with value '[2]'
Tried like this:
ArrayList.metaClass.compareTo = {arg -> this?.size() <=> arg?.size() }
[1]<=>[2]
It doesn't work.
There is still exception rises groovy.lang.GroovyRuntimeException: Cannot compare java.util.ArrayList with value '[1]' and java.util.ArrayList with value '[2]'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一种方法是实现 Comparator 接口。
另一种方法是根据需要使用
metaClass
,但是您将无法使用<=>
运算符,因为List
没有t 实现Comparable
。One approach is to implement the
Comparator
interface.Another is to use the
metaClass
as you wanted, however you will not be able to use the<=>
operator sinceList
doesn't implementComparable
.我应该问...你为什么要这么做?
比较运算符都依赖于实现 Comparable 的类,而不仅仅是 CompareTo 方法,而且我认为不可能在现有类上强制使用该接口。
faik,你需要另一种方法
i should ask... why do you want to do that?
the comparison operators all depend on the class implementing Comparable and not just on the compareTo method, and i don't think it's possible to force that interface on an existing class.
afaik, you will need another approach
您可以将列表标记为可比较:
You can mark list as Comparable: