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

一曲冷凌霜 提交于 2019-12-01 00:00:03

问题


I've tried:

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

I want to be able to use this as a set, but even if I pass it explicitly, 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)

回答1:


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<String> 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<String> 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



回答2:


Groovy >= 2.4.0
Setting interpreterMode to true in groovy shell by

:set interpreterMode true

should fix this issue

Groovy < 2.4.0
Adding a type to the variable makes it a local variable which is not available to shell's environment.

use as below in 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>


来源:https://stackoverflow.com/questions/27848281/how-do-you-declare-and-use-a-set-data-structure-in-groovysh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!