我写了一个方法来检查字符串是否只有唯一字符。我向它发送明显的非唯一字符字符串 "11"
,它返回 true
而不是 false
。这是因为在 if (tab.get(c) == null)
中的 get(c)
中返回 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?! */
}
最佳答案
您正在按字符获取,但您的 map 的键是 Boolean
.您希望 key 为 Character
值为Boolean
:
HashMap<Character, Boolean> tab = new HashMap<Character, Boolean>();
Character c;
for (int i = 0; i < s.length(); ++i) {
c = new Character(s.charAt(i));
if (tab.get(c) == null)
tab.put(c, Boolean.TRUE);
else
return false;
}
return true;
话虽如此:
- 您不需要创建新的
Character
明确地。拳击将为您做到这一点。 - 使用
HashSet<Character>
跟踪您到目前为止看到的字符会更简单。
例如:
Set<Character> set = new HashSet<Character>();
for (int i = 0; i < s.length(); i++) {
Character c = s.charAt(i);
// add returns true if the element was added (i.e. it's new) and false
// otherwise (we've seen this character before)
if (!set.add(c)) {
return false;
}
}
return true;
关于java - 为什么 HashMap 的 get() 不应该返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18967995/