java - 为什么 HashMap 的 get() 不应该返回 null?

标签 java hashmap

我写了一个方法来检查字符串是否只有唯一字符。我向它发送明显的非唯一字符字符串 "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/

相关文章:

java - 从 JAVA 中的多维 JSON 映射检索数据

java - 将值插入 HashMap 无法正常工作

java - @autowired 不适用于 struts2 + spring

java - 使用 elasticSearch 和 Spring Boot 创建 bean 时出错

java - 使用HashMap和List解析文本文件

Java - 在不覆盖的情况下向现有 HashMap 键添加另一个字符串值?

python - "Bucket"在python中是什么意思?

java - 在 Java 中通过 DataOutputStream 发送多个 POST 请求

java - 尝试使用 eclipse 创建可运行的 jar 文件时收到警告消息

java - 启动画面中的 GIF 不流畅