4

我一定快疯了,但为什么 Groovy findIndexValues 会返回List<long>?我可以得到整数的索引吗?

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

以上将崩溃,因为 foo 集合无法处理 long 作为访问索引。我没有使用应有的语言吗?

4

2 回答 2

5

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

您可以使用以下方法解决它:

indices.each { println foo[it as int] }
于 2012-12-06T20:19:39.173 回答
2

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

foo = ['a','b','d','e', 'e','e']
indices  = foo.findIndexValues { it == 'e'}.collect { it as Integer }
indices.each { println foo[it] }
于 2018-03-21T03:01:10.927 回答