久久久久久久av_日韩在线中文_看一级毛片视频_日本精品二区_成人深夜福利视频_武道仙尊动漫在线观看

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

Why does this code sometimes throw a NullPointerException?(為什么這段代碼有時會拋出 NullPointerException?)
本文介紹了為什么這段代碼有時會拋出 NullPointerException?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

考慮以下 Java 源代碼:

Consider the following Java source:

if( agents != null ) {
  for( Iterator iter = agents.keySet().iterator(); iter.hasNext(); ) {
    // Code that uses iter.next() ...
    //
  }
}

agents 是一個 HashMap.

為什么 for 語句有時會拋出 NullPointerException?

Why does the for statement sometimes throw a NullPointerException?

謝謝.

推薦答案

線程安全

如果您的代碼是多線程的,那么這是可能的.例如:

If your code is multi-threaded, then it is possible. For example:

public class C {
  private Hashtable agents = new Hashtable();

  public iterate() {
    if( agents != null ) {
      for (Iterator iter = agents.keySet().iterator(); iter.hasNext();) {
        // Code goes here
      }
    }
}

如果另一個線程在 if 語句執行后立即將 agents 設置為 null(但在 for 循環之前),然后你會得到一個 NullPointerException.通過使用訪問器(結合惰性初始化)來避免這種情況.

If another thread sets agents to null immediately after the if statement executes (but before the for loop), then you will get a NullPointerException. Avoid this by using accessors (combined with lazy initialization).

另外,正如其他人所提到的,如果可能,請避免使用泛型來支持此類循環構造.有關詳細信息,請參閱其他答案.

Also, as others have mentioned, avoid such looping constructs in favour of generics, if possible. See other answers for details.

訪問器提供保護

如果您始終使用以下模式,您的源代碼中將永遠不會出現 NullPointerException(另一方面,第三方代碼可能存在導致您的代碼間接失敗的問題,這是無法輕易避免的).

If you always use the following pattern you will never have NullPointerExceptions in your source code (third-party code, on the other hand, might have issues that cause your code to fail, indirectly, which cannot be easily avoided).

public class C {
  private Hashtable agents;

  private synchronized Hashtable getAgents() {
    if( this.agents == null ) {
      this.agents = new Hashtable();
    }

    return this.agents;
  }

  public iterate() {
    Hashtable agents = getAgents();

    for (Iterator iter = agents.keySet().iterator(); iter.hasNext();) {
      // Code goes here
    }
  }
}

遍歷代理的代碼不再需要檢查 null.由于許多原因,此代碼更加健壯.您可以用 Hashmap(或任何其他抽象數據類型,例如 ConcurrentHashMap<K,V>)替換 Hashtable.

The code that iterates over the agents no longer needs to check for null. This code is much more robost for many reasons. You can substitute Hashmap (or any other abstract data type, such as ConcurrentHashMap<K,V>) for Hashtable.

開閉原則

如果您覺得自己的時間特別慷慨,您可以這樣做:

If you were feeling especially generous with your time you could go as far as:

public class C {
  private Hashtable agents;

  private synchronized Hashtable getAgents() {
    if( this.agents == null ) {
      this.agents = createAgents();
    }

    return this.agents;
  }

  public iterate() {
    Iterator i = getAgentKeyIterator();

    while( i.hasNext() ) {
      // Code that uses i.next() ...
    }
  }

  protected Hashtable createAgents() {
    return new Hashtable();
  }

  private Iterator getAgentKeyIterator() {
    return getAgentKeys().iterator();
  }

  private KeySet getAgentKeys() {
    return getAgents().keySet();
  }
}

這將允許子類(由其他開發人員編寫)替換他們自己正在使用的抽象數據類型的子類(允許系統更大的靈活性以符合 開放-封閉原則),無需修改(或復制/浪費)您的原創作品.

This would allow subclasses (written by other developers) to substitute their own subclass of the abstract data type being used (allowing the system greater flexibility in keeping with the Open-Closed Principle), without having to modify (or copy/waste) your original work.

這篇關于為什么這段代碼有時會拋出 NullPointerException?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Convert List of Strings into Map using Java-8 Streams API(使用 Java-8 Streams API 將字符串列表轉換為 Map)
Getting data from JSON(從 JSON 獲取數據)
java linkedhashmap iteration(javalinkedhashmap迭代)
Converting a list of objects to Map(將對象列表轉換為 Map)
Create a HashMap with a fixed Key corresponding to a HashSet. point of departure(用一個固定的Key對應一個HashSet創建一個HashMap.出發點)
HttpMessageConverter exception : RestClientException: Could not write request: no suitable HttpMessageConverter found(HttpMessageConverter 異常:RestClientException:無法寫入請求:找不到合適的 HttpMessageConverter) - IT屋-程序員
主站蜘蛛池模板: 欧美一级大片免费看 | 成人免费视频网站在线看 | 欧美久久视频 | 龙珠z在线观看 | 国产高清久久久 | 亚洲一区在线播放 | 国产一区二区在线观看视频 | 狠狠骚| 狠狠干美女| 国产欧美精品 | 视频一区在线观看 | 伊人免费网 | 国产福利资源 | 中文字幕国产一区 | 精品久久中文字幕 | 国产精品久久国产精品 | 国产精品美女久久久久aⅴ国产馆 | 日韩欧美在线观看 | 狠狠干综合视频 | 日韩欧美国产一区二区 | 91在线网站 | 欧美一区二区 | 在线国产精品一区 | 久热爱 | 亚洲福利 | 色网在线观看 | 中文字幕精品一区久久久久 | 欧美成人精品激情在线观看 | 波多野结衣中文字幕一区二区三区 | 伊人狠狠 | 国产精品我不卡 | 中文字幕一区二区三区在线乱码 | 欧美日韩在线视频一区 | 亚洲精品成人在线 | h片在线免费看 | 欧美天堂在线 | 亚洲精品3 | 日本a∨视频 | www亚洲精品 | 天天天天天操 | 毛片在线免费播放 |