Java – why does get () of HashMap return null when it should not?

I wrote a method to check whether a string has only unique characters I send the apparently non unique string "11", which returns true instead of false This is because null is returned in get (c) in if (tab. Get (c) = = null), even if the character "1" is already in the HashMap

What can I do to get the expected behavior?

/* 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?! */
}

Solution

You get things by character, but the key of the map is Boolean You want the key to be character and the value to be 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;

Then again:

>You do not need to explicitly create a new role Boxing will do that for you. > It will be easier to use HashSet < character > to track the characters you have seen so far

For example:

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;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>