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

為什么這段代碼有時(shí)會(huì)拋出 NullPointerException?

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

問題描述

考慮以下 Java 源代碼:

Consider the following Java source:

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

agents 是一個(gè) HashMap.

為什么 for 語句有時(shí)會(huì)拋出 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
      }
    }
}

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

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).

另外,正如其他人所提到的,如果可能,請(qǐng)避免使用泛型來支持此類循環(huán)構(gòu)造.有關(guān)詳細(xì)信息,請(qǐng)參閱其他答案.

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

訪問器提供保護(hù)

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

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(或任何其他抽象數(shù)據(jù)類型,例如 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.

開閉原則

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

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();
  }
}

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

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.

這篇關(guān)于為什么這段代碼有時(shí)會(huì)拋出 NullPointerException?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!

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

相關(guān)文檔推薦

Convert List of Strings into Map using Java-8 Streams API(使用 Java-8 Streams API 將字符串列表轉(zhuǎn)換為 Map)
Getting data from JSON(從 JSON 獲取數(shù)據(jù))
java linkedhashmap iteration(javalinkedhashmap迭代)
Converting a list of objects to Map(將對(duì)象列表轉(zhuǎn)換為 Map)
Create a HashMap with a fixed Key corresponding to a HashSet. point of departure(用一個(gè)固定的Key對(duì)應(yīng)一個(gè)HashSet創(chuàng)建一個(gè)HashMap.出發(fā)點(diǎn))
HttpMessageConverter exception : RestClientException: Could not write request: no suitable HttpMessageConverter found(HttpMessageConverter 異常:RestClientException:無法寫入請(qǐng)求:找不到合適的 HttpMessageConverter) - IT屋-程序員
主站蜘蛛池模板: 精品久久久网站 | 日韩成人免费视频 | 99一级毛片 | 风间由美一区二区三区在线观看 | 国产99久久 | 午夜伦理影院 | 国产精品国产三级国产aⅴ中文 | 99精品一区二区 | 久久久精品网 | 日韩成人在线观看 | 久久精品视频99 | 成人自拍视频网站 | 精品少妇一区二区三区在线播放 | 欧美日韩中文在线 | 国产91久久久久久久免费 | 国产精品爱久久久久久久 | 国产精品国产a | 欧美亚洲另类在线 | 蜜桃视频在线观看免费视频网站www | 精品久久久久久久 | 亚洲精品黄色 | 国产一在线| 成人动慢 | 欧美日韩国产精品一区二区 | 男女啪啪高潮无遮挡免费动态 | 精品无码久久久久久久动漫 | 久久久久久高潮国产精品视 | 极品在线 | 91精品91久久久 | 一区二区三区视频在线观看 | 天堂在线免费视频 | 日本精品视频在线观看 | 三级黄色片在线观看 | 一级黄色片网址 | 国产在线观看av | 亚洲综合国产 | 日本视频在线播放 | 91精品国产色综合久久不卡98 | 国产成人网 | 免费av播放| 九九久视频 |