Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么使用HashMap';s get()在不应';T_Java_Hashmap - Fatal编程技术网

Java 为什么使用HashMap';s get()在不应';T

Java 为什么使用HashMap';s get()在不应';T,java,hashmap,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&

我编写了一个方法来检查字符串是否只有唯一的字符。我向它发送明显的非唯一字符串
“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?! */
}
/*检查字符串是否仅包含唯一字符*/
公共静态布尔值isUniqueChars(字符串s){
HashMap选项卡=新建HashMap();
字符c;
对于(int i=0;i
您是通过字符获取的,但地图的键是
布尔值。您希望键为
字符
,值为
布尔值

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;

也许你正在做的是一个“值”而不是键,所以试着把你的hashmap倒过来

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

然后,用与tab.get(c)相同的方法获取。你真的用布尔值作为键吗?还是键入错误?不要使用
HashMap
,你所需要的只是一个
HashSet
。除了Jon和Surveon所说的-使用
Set
而不是
Map
。你肯定是对的。这是个错误。现在我明白了。谢谢将来使用
Map
时,请使用
myMap.containsKey(keyObject)
确定该键是否已存在于Map中。是否设置为与HashSet相同?@Blam:Oops,意思是使用
HashSet
作为实现,但
Set
作为变量。固定的。
HashMap<Character,Boolean> tab = new HashMap<Character, Boolean>();