Considérez cette classe:Pourquoi cette récupération de carte produit-elle un NPE?
public class TestMap extends HashMap<String, Float> {
public static void main(String[] args) {
TestMap tm = new TestMap();
tm.put("A", 0F);
tm.put("B", null);
String[] keys = new String[]{"A", "B"};
for (String key : keys) {
System.out.println(key);
Float foo = (tm == null ? 0F : tm.get(key));
// Float foo = tm.get(key);
System.out.println(foo);
}
}
}
NullPointerException est produit sur la ligne Float foo =...
au cours de la seconde itération de la boucle:
A
0.0
B
Exception in thread "main" java.lang.NullPointerException
at TestMap.main(TestMap.java:14)
Si je remplace la ligne existante avec la ligne commentée immédiatement au-dessous fonctionne comme prévu, assigner foo = null. Pourquoi le comportement est-il différent dans ces deux cas?
Je déclarerais 'final TestMap tm = ...' et renoncer à la vérification 'tm == null'. –