我试过了:
groovy:000> Set<String> s = ["a", "b", "c", "c"]
===> [a, b, c]
groovy:000> s
Unknown property: s
我希望能够将其用作一个集合,但是即使我显式传递它,它也会将其变成ArrayList:
groovy:000> joinList(["a", "b", "c", "c"])
ERROR groovy.lang.MissingMethodException:
No signature of method: groovysh_evaluate.joinList() is applicable for argument types: (java.util.ArrayList) values: [[a, b, c, c]]
Possible solutions: joinList(java.util.Set)
只会出现此问题,因为您正在使用Groovy Shell来测试您的代码。我没有使用Groovy shell,但是似乎忽略了类型,例如
Set<String> s = ["a", "b", "c", "c"]
相当于
def s = ["a", "b", "c", "c"]
后者当然会创建一个List
。如果您改为在Groovy控制台中运行相同的代码,则会看到它确实创建了一个Set
Set<String> s = ["a", "b", "c", "c"]
assert s instanceof Set
Set
在Groovy中创建A的其他方法包括
["a", "b", "c", "c"].toSet()
或者
["a", "b", "c", "c"] as Set
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句