[a, b, c] groov...">

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

I tried:

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

I want to use this as a collection, but even if I explicitly pass it on, it turns it into an 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)
+4
source share
2 answers

This problem only occurs because you use the Groovy shell to verify the code. I don't use the Groovy shell a lot, but it seems to ignore types like

Set<String> s = ["a", "b", "c", "c"]

equivalently

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

and the latter, of course, creates a List. If you run the same code in the Groovy console, you will see that it actually createsSet

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

Other ways to create SetGroovy include

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

or

["a", "b", "c", "c"] as Set
+12
source

Groovy >= 2.4.0
interpreterMode true groovy

:set interpreterMode true

Groovy 2.4.0
, .

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>
+11

Source: https://habr.com/ru/post/1570506/


All Articles