[a, b, c] groovy:000> s Unknown property: s 我希望能够-6ren">
gpt4 book ai didi

groovy - 在 groovysh 中如何声明和使用 Set 数据结构?

转载 作者:行者123 更新时间:2023-12-04 00:39:49 31 4
gpt4 key购买 nike

我试过:

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", "b", "c", "c"].toSet()


["a", "b", "c", "c"] as Set

关于groovy - 在 groovysh 中如何声明和使用 Set 数据结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27848281/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com