我写了一个方法来检查一个字符串是否只有唯一字符。我将明显的非唯一字符字符串发送给它"11"
,它返回true
而不是false
. 发生这种情况是因为在get(c)
in 中if (tab.get(c) == null)
返回null
,即使字符'1'
已经在 HashMap 中。
我该怎么做才能获得预期的行为?
/* Check if a string contains only unique characters */
public static boolean isUniqueChars(String s) {
HashMap<Boolean, Character> tab = new HashMap<Boolean, Character>();
Character c;
for (int i = 0; i < s.length(); ++i) {
c = new Character(s.charAt(i));
if (tab.get(c) == null)
tab.put(Boolean.TRUE, c);
else
return false;
}
return true;
}
public static void main(String[] args) {
String s = "11";
System.out.println(isUniqueChars(s)); /* prints true! why?! */
}