【问题标题】:How do you declare and use a Set data structure in groovysh?如何在 groovysh 中声明和使用 Set 数据结构?
【发布时间】:2015-01-08 19:42:51
【问题描述】:

我试过了:

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 groovysh


    【解决方案1】:

    这个问题只是因为您使用 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
    

    在 Groovy 中创建 Set 的其他方法包括

    ["a", "b", "c", "c"].toSet()
    

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

    【讨论】:

    • 啊,好吧。所以你建议使用控制台来解决这个问题?
    • @smilingcow 是的,我不知道为什么 Groovy shell 会忽略这样的类型,但我倾向于使用控制台来代替这些类型的快速测试
    • groovysh 不是没有 REPL
    • 有趣。 ["a", "b", "c", "c"] as Set 使我的单元测试失败,但是 ["a", "b", "c", " c"].toSet() 工作正常。我正在使用 Spock。
    • @PatrycjaK 我刚刚在 Spock 中也对它感兴趣,因为有一个区别:......当 Set 创建一个 LinkedHashSet,.toSet() 创建一个 HashSet。这打破了我的嘲笑,因为在生产代码中使用了 KeySet,它是 HashSet 的祖先,但不是 LinkedHashSet。
    【解决方案2】:

    Groovy >= 2.4.0
    在 groovy shell 中将 interpreterMode 设置为 true

    :set interpreterMode true
    

    应该解决这个问题

    Groovy
    为变量添加类型使其成为 shell 环境不可用的局部变量。

    groovysh中使用如下

    groovy:000> s = ['a', 'b', 'c', 'c'] as Set<String>
    ===> [a, b, c]
    groovy:000> s
    ===> [a, b, c]
    groovy:000> s.class
    ===> class java.util.LinkedHashSet
    groovy:000>
    

    【讨论】:

    • 您在示例中省略了类型,因此一切都按预期进行。知道为什么 Groovy Shell 似乎忽略了导致这个问题中描述的那种误解的类型吗?
    • 向变量添加类型使其成为局部变量,shell 环境无法使用该变量。 @多纳尔
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多