我寫了一個方法來檢查一個字符串是否只有唯一的字符。我發給它明顯的非唯一字符串"11"
,它返回true
而不是false
。發生這種情況的原因是get(c)
中的if (tab.get(c) == null)
返回null
,即使字符'1'
已經在HashMap中。爲什麼HashMap的get()在它不應該返回時返回null?
我能做些什麼來獲得預期的行爲?
/* 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?! */
}
你真的使用布爾值作爲鍵還是錯字? – Surveon
不要使用'HashMap',你只需要一個'HashSet'。 – Marcelo
除了Jon和安業長說的話 - 使用'Set'代替'Map '可能會更好。 –