ãã®åãå¾è¼©ãããããã¦ã¡ãã£ã¨ã³ã£ãããããã¨ã
ä¸è¦ããã¨ãã ã®ã·ã³ã°ã«ãã³ãã¿ã¼ã³ã®ã¯ã©ã¹ãããªããåããªãã¨è¨ããã¾ããã
public class Sample { private static final Sample instance = new Sample(); private static Map<String, String> map = null; private Sample(){ map = Collections.synchronizedMap(new HashMap<String, String>()); } public static Sample getInstance(){ return instance; } public void set(String key, String value){ map.put(key, value); // NullPointerExceptionï¼ } }
ä¸æè°ã«æã£ã¦ãããã°ããããsetã¡ã½ãã㧠map ã null ã«ãªã£ã¦ãããããã§NullPointerException ãåºã¾ããã
ãããã«å®£è¨æã« null ã代å
¥ãã¦ã¾ããã»ã»ã»ã
ã§ããã¡ããã¨ã³ã³ã¹ãã©ã¯ã¿ã§åæåãã¦ããããã«è¦ãã¾ãã
ã»ã»ã»ã¯ã©ã¹å¤æ°ã®åæåã¯ç¢ºãä¸ããã®é ã®ããºï¼*1
ã¨ãããã¨ã§ãããã«ãããã°ãã¦ã¿ããããããåå ã§ããã
ã©ããããã¨ãã¨ããã¨ã
- instance å¤æ°ãåæå
- ãã®æãã³ã³ã¹ãã©ã¯ã¿ã§ map ã«ã¤ã³ã¹ã¿ã³ã¹ãä»£å ¥
- map ã null ã§åæå
ã¨ããé åºã»ã»ã»ã
ã¨ããããã宣è¨æã® null åæåãããããã¡ããã¨åãã¾ããã
ã§ããããã¯ã¡ãã£ã¨ä¸æè°ã
å¤æ°å®£è¨æã®åæåãããã®å¤æ°ã使ãããããã¨ã«è¡ããã¦ãã¾ãã
ãã®è¾ºã®åãã¯ãæ°ãã¤ããªãã¨å¤ãªã¯ã¾ãæ¹ããããã§ããã»ã»ã»ã
ä»ã«ããããããä¾ã¯ãã£ã¦ãã¾ãããã§ãï¼ããã Effective Java ã«ãè¼ã£ã¦ãããããªâ¦ï¼ã
public class Sample { private static final Sample instance = new Sample(); private static final Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>()); private Sample(){ map.put("Test", "NG"); // ãã㧠NullPointerExceptionï¼ } public static Sample getInstance(){ return instance; } }
æè¨ï¼ã·ã³ã°ã«ãã³ã¤ã³ã¹ã¿ã³ã¹ã® static 宣è¨ã¯ä¸çªæå¾ã«æ¸ã
2011/7/18 追è¨ï¼
ã³ã¡ã³ããããã ãã¾ããã
ToriKen
ãstaticå¤æ°ã®åæåããã³ã³ã¹ãã©ã¯ã¿ãªã©ã®ã¤ã³ã¹ã¿ã³ã¹ã¡ã½ããã§è¡ã£ã¦ãããã¨ããæ ¹æ¬çãªåå ã ã¨æãã¾ãã
解決æ³ã¨ãã¦ã¯ããmapãã¤ã³ã¹ã¿ã³ã¹å¤æ°ã«ããããããã¯ãmapã®åæåãstaticã¤ãã·ã£ã©ã¤ã¶ã§è¡ããã®äºæã«ãªãã¨æãã¾ããã
ãææããã ããããã«ãmapãã¤ã³ã¹ã¿ã³ã¹å¤æ°ã«ãããã«ä¿®æ£ããã¨ãããé çªã«é¢ä¿ãªãã¡ããã¨åãããã«ãªãã¾ããï¼
ãããæ¸ãã¦ããã¨ãã«ãstatic å¤æ°ã¨ã¤ã³ã¹ã¿ã³ã¹å¤æ°ãåºå¥ããã«èãã¦ãã¾ã£ã¦ãã¾ããã»ã»ã»ã
ï¼ToriKenããããããã¨ããããã¾ããï¼
ä¿®æ£å¾ã®ã½ã¼ã¹ï¼
public class Sample { private static final Sample instance = new Sample(); private Map<String, String> map = null; (以ä¸ç¥)
*1:念ã®ãããJavaè¨èªä»æ§ç¬¬3çã§ç¢ºèªããã¨ããã12.4.1ãéçåæååã¨ã¯ã©ã¹å¤æ°åæååã¯ããã¹ãé ã«å®è¡ãããã»ã»ã»ãã¨ãªã£ã¦ããã®ã§ãããã§ãã£ã¦ã¾ãããã ãã8.3.2.1ãäºç´°ãªç¹ã§ããããstaticå¤æ°ãfinalã¨ãã¦å®£è¨ããã¦ããããã¤ã³ã³ãã¤ã«æã®å®æ°å¤ã§åæåãããå ´åãããã¯å®è¡æã«æåã«åæåããããï¼ä¸ç¥ï¼ãããã£ãå¤æ°ã¯ãå®æ°ãã§ãããã©ã®ãããªããã°ã©ã ããã£ã¦ãã¦ãããã©ã«ãã®åæå¤ãåå¾ããããã¨ã¯ãªããã¨ãããªã®ã§ãã¯ã©ã¹ã®finalå®æ° -> ã¯ã©ã¹å¤æ°åæåãæ£ç¢ºãªé åºã§ãã