簡體   English   中英

為什么這段代碼會拋出NullPointerException?

[英]why does this code throw a NullPointerException?

最終我得到了答案,但它讓我困惑了一段時間。

為什么以下代碼在運行時拋出NullPointerException?

import java.util.*;

class WhyNullPointerException {
    public static void main( String [] args ){
       // Create a map
        Map<String,Integer> m = new HashMap<String,Integer>();
        // Get the previous value, obviously null.
        Integer a = m.get( "oscar" );
        // If a is null put 1, else increase a
        int p = a == null ? 
            m.put( "oscar", 1) : 
            m.put( "oscar", a++ ); // Stacktrace reports Npe in this line
    }
}

因為當你嘗試將它分配給int m.put返回null (表示沒有“previous”值)。 Integer p替換int p它會起作用。

這在JLS 5.1.8中指定:

5.1.8拆箱轉換

在運行時,取消裝箱轉換過程如下:

  • 如果rnull ,則取消裝箱轉換會拋出NullPointerException

與問題無關,只考慮DRY的一個側面建議,考慮這樣寫:

    Integer p = m.put("oscar", a == null ? 1 : a++);

它更具可讀性:)

您將int p賦值給m.put()的返回值。 但是put()在這種情況下返回null ,並且你不能將int賦值為null

從Javadocs for HashMap.put()

返回:與指定鍵關聯的上一個值,如果沒有鍵映射,則返回 null。

暫無
暫無

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

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