如何使 Groovy 数组具有可比性?

发布于 2024-10-17 01:43:19 字数 314 浏览 3 评论 0原文

尝试这样:

   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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

坚持沉默 2024-10-24 01:43:19

一种方法是实现 Comparator 接口。

另一种方法是根据需要使用 metaClass,但是您将无法使用 <=> 运算符,因为 List 没有t 实现Comparable

List.metaClass.compareTo = { Collection other ->
    delegate.size() <=> other?.size()
}

def x = [1, 2, 3]
def y = [4, 5]

println x.compareTo(y)  // but x <=> y won't work

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 since List doesn't implement Comparable.

List.metaClass.compareTo = { Collection other ->
    delegate.size() <=> other?.size()
}

def x = [1, 2, 3]
def y = [4, 5]

println x.compareTo(y)  // but x <=> y won't work
梦晓ヶ微光ヅ倾城 2024-10-24 01:43:19

我应该问...你为什么要这么做?
比较运算符都依赖于实现 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

染火枫林 2024-10-24 01:43:19

您可以将列表标记为可比较:

List.metaClass.compareTo = { other ->
    delegate[0] <=> other[0]
}
assert ([1,2] as Comparable) <=> ([3,4] as Comparable) == -1
assert ([3,4] as Comparable) <=> ([1,2] as Comparable) == 1
assert ([3,4] as Comparable) <=> ([3] as Comparable) == 0

You can mark list as Comparable:

List.metaClass.compareTo = { other ->
    delegate[0] <=> other[0]
}
assert ([1,2] as Comparable) <=> ([3,4] as Comparable) == -1
assert ([3,4] as Comparable) <=> ([1,2] as Comparable) == 1
assert ([3,4] as Comparable) <=> ([3] as Comparable) == 0
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文