簡體   English   中英

HashMap/Hashtable 不返回 int 作為 for 循環中的鍵值

[英]HashMap/Hashtable not returning int as key value in for loop

當我嘗試在 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);

提前感謝您的幫助! 羅漢。

for 循環運行,直到其條件不滿足(在您的情況下,直到j <= 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

出於這個原因,將在 for 循環的每次迭代中調用map.get(c) 如果您碰巧從map刪除了鍵為c的條目,則從Map#get返回的值為null ,這就是導致NullPointerException原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM