【问题标题】:How to make Groovy arrays comparable?如何使 Groovy 数组具有可比性?
【发布时间】:2011-06-24 06:43:20
【问题描述】:

试过这样:

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

【问题讨论】:

    标签: collections groovy metaclass


    【解决方案1】:

    一种方法是实现Comparator 接口。

    另一种方法是根据需要使用metaClass,但是您将无法使用&lt;=&gt; 运算符,因为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
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-10-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多