加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 05:01:57 所属栏目:Java 来源:网络整理
导读:我写了一个方法来检查一个字符串是否只有唯一的字符.我发送明显的非唯一字符串“11”,它返回true而不是false.这是因为在if(tab.get(c)== null)中的get(c)中返回null,即使字符“1”已经在HashMap中. 我该怎么做才能获得预期的行为? /* Check if a string con
我写了一个方法来检查一个字符串是否只有唯一的字符.我发送明显的非唯一字符串“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?! */
}

解决方法

你是按角色取物,但地图的键是布尔值.您希望键为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;

话说回来:

>您无需显式创建新角色.拳击会为你做到这一点.
>使用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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读