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

时间:2011-02-09 16:34:18

标签: collections groovy metaclass

试过这样:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

答案 2 :(得分: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