【问题标题】:HashMap/Hashtable not returning int as key value in for loopHashMap/Hashtable 不返回 int 作为 for 循环中的键值
【发布时间】:2018-11-11 00:14:57
【问题描述】:

当我尝试在 for 循环中访问 map.get(c) 时(如版本 2 所示),它返回空值并将上限设置为空,从而导致空指针异常。另一方面,如果我创建 end 变量并为其分配 map.get(c) 值(如版本 1 所示),它可以正常工作。那么,请你解释一下为什么?

版本 1:完美运行

    int count=0;
    int st=0;
    string s = "abcabcbb";

    Hashtable<Character, Integer> map = new Hashtable<Character, Integer>();

    char[] str = s.toCharArray();
    for(int i=0; i<str.length; i++){
        char c = str[i];
        if(map.get(c)==null){
            map.put(c, i);

            if(count < map.get(c) - st + 1){
                count = map.get(c) - st + 1;
            };
        }


        else {
            int end = map.get(c);     // End variable --> returns int value as expected

            for(int j=st; j<=end; j++){
                map.remove(str[j]);
                st = j+1;
            }
            map.put(c,i);
        }

    }

    System.out.println(count);

版本 2:给出空指针异常

    int count=0;
    int st=0;
    string s = "abcabcbb";

    Hashtable<Character, Integer> map = new Hashtable<Character, Integer>();

    char[] str = s.toCharArray();
    for(int i=0; i<str.length; i++){
        char c = str[i];
        if(map.get(c)==null){
            map.put(c, i);

            if(count < map.get(c) - st + 1){
                count = map.get(c) - st + 1;
            };
        }


        else {
            //int end = map.get(c);     // End variable commented

            for(int j=st; j<=map.get(c); j++){   // replaced end w map.get(c) --> returns null instead of int
                map.remove(str[j]);
                st = j+1;
            }
            map.put(c,i);
        }

    }

    System.out.println(count);

提前感谢您的帮助! 罗汉。

【问题讨论】:

标签: java hashmap hashtable


【解决方案1】:

for 循环一直运行直到其条件不满足(在您的情况下,直到 j &lt;= map.get(c)false)。这个条件也没有缓存,如下代码的输出所示:

public static void main(String[] args) {
    for (int i = 0; i < getCondition(); i++) {

    }
}

private static int getCondition() {
    System.out.println("Test");
    return 3;
}

输出:

Test
Test
Test
Test

因此,map.get(c) 将在 for 循环的每次迭代中被调用。如果您碰巧从map 中删除了键为c 的条目,则从Map#get 返回的值是null,这就是导致NullPointerException 的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多