jvm中的Set.contains()不适用于Character类

时间:2014-05-17 00:38:23

标签: collections groovy

HashMap<Character, Character> charMap = new HashMap<Character ,Character>();
charMap['{'] = '}';
charMap['['] = ']';
charMap['('] = ')';

//println charMap.keySet()
Character ch = '{'
println charMap.keySet().contains(ch)

它只是打印错误,而很明显我的设置包含&#39; {&#34;,任何想法为什么会发生这种情况? (我正在使用groovy进行测试......)

感谢。

1 个答案:

答案 0 :(得分:4)

'{'是一个字符串,而不是groovy中的字符。为了证明这一点,只需在最后一行打印:

println charMap.keySet()*.class

必须明确地将其类型化为字符:

HashMap<Character, Character> charMap = new HashMap<Character ,Character>();
charMap['{' as char] = '}';
charMap['['] = ']';
charMap['('] = ')';

//println charMap.keySet()
Character ch = '{'
println charMap.keySet().contains(ch)

这是它的工作原理:

//String
assert 'a'.class == String

//Character
def c1= 'a' as char, c2= (char)'b' 
def c3= new Character(c2), c4= c2.charValue()
[c1, c2, c3, c4].each { assert it.class == Character }
assert c2 == c3 && c1 != c2
assert c1 < c2 && c1.compareTo(c2) == -1
assert c2.toString().class == String