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]'

4

3 回答 3

1

一种方法是实现Comparator接口。

另一种是根据需要使用metaClass,但是您将无法使用<=>运算符,因为List没有实现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
于 2011-02-11T08:07:40.157 回答
0

我应该问……你为什么要那样做?
比较运算符都依赖于实现 Comparable 的类,而不仅仅是 compareTo 方法,我认为不可能在现有类上强制使用该接口。
afaik,您将需要另一种方法

于 2011-02-11T07:02:06.323 回答
0

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

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
于 2016-02-19T07:53:06.257 回答