【问题标题】:Groovy findIndexValues return List<Long>Groovy findIndexValues 返回 List<Long>
【发布时间】:2012-12-06 20:03:53
【问题描述】:

我一定快疯了,但为什么 Groovy findIndexValues 返回List&lt;long&gt;?我可以获取 Integer 的索引吗?

foo = ['a','b','d','e', 'e','e']
indices  = foo.findIndexValues { it == 'e'}
indices.each { println foo[it] }

上面会崩溃,因为 foo 集合不能处理 long 作为访问索引。我没有使用应有的语言吗?

【问题讨论】:

    标签: collections types groovy


    【解决方案1】:

    这就是该方法的工作原理。它使用迭代器遍历集合并跟踪匹配的索引。理论上,它支持大于Integer.MAX_VALUE 的集合,尽管我怀疑这在实践中是否有用。

    您可以通过以下方式解决它:

    indices.each { println foo[it as int] }
    

    【讨论】:

    • 我觉得这是一个糟糕的实施决定。特别是当文档没有说明时。我想我只能忍受它。
    • findIndexValues 在可迭代对象上工作,因此可以拥有比列表更多的元素
    【解决方案2】:

    不要在每次使用索引时都进行转换,而是在初始分配时将其全部转换。

    foo = ['a','b','d','e', 'e','e']
    indices  = foo.findIndexValues { it == 'e'}.collect { it as Integer }
    indices.each { println foo[it] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-09
      • 2020-12-31
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多