How do you declare and use a Set data structure in groovysh?

前端 未结 2 596
感动是毒
感动是毒 2021-01-11 18:41

I\'ve tried:

groovy:000> Set s = [\"a\", \"b\", \"c\", \"c\"]
===> [a, b, c]
groovy:000> s
Unknown property: s

I wa

2条回答
  •  一生所求
    2021-01-11 18:52

    This problem only occurs because you're using the Groovy Shell to test your code. I don't use the Groovy shell much, but it seems to ignore types, such that

    Set s = ["a", "b", "c", "c"]
    

    is equivalent to

    def s = ["a", "b", "c", "c"]
    

    and the latter does of course create a List. If you run the same code in the Groovy console instead, you'll see that it does actually create a Set

    Set s = ["a", "b", "c", "c"]
    assert s instanceof Set
    

    Other ways to create a Set in Groovy include

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

    or

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

提交回复
热议问题