2013-09-23 62 views
3

我写了一个方法来检查一个字符串是否只有唯一的字符。我发给它明显的非唯一字符串"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?! */ 
} 
+5

你真的使用布尔值作为键还是错字? – Surveon

+2

不要使用'HashMap',你只需要一个'HashSet'。 – Marcelo

+1

除了Jon和安业长说的话 - 使用'Set '代替'Map '可能会更好。 –

回答

11

取由字符,但地图的关键是Boolean。你想关键是CharacterBoolean

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; 
+0

谢谢!现在很明显。 –

+0

设置与HashSet相同吗? – Paparazzi

+0

@Blam:糟糕,本意是使用'HashSet'作为实现,但设置'变量。固定。 –

1

也许你正在做的 “价值” 不是一个GET key.so尝试扭转你的HashMap作为

HashMap<Character,Boolean> tab = new HashMap<Character, Boolean>(); 

那就不要让你以同样的方式做tab.get(c)。