Consider the following Java source:
if( agents != null ) {
for( Iterator iter = agents.keySet().iterator(); iter.hasNext(); ) {
// Code that uses iter.next() ...
//
}
}
The agents is a HashMap.
Why does the for statement sometimes throw a NullPointerException?
Thank you.
Thread Safety
If your code is multi-threaded, then it is possible. For example:
If another thread sets
agentstonullimmediately after theifstatement executes (but before theforloop), then you will get aNullPointerException. 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.
Accessors offer Protection
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).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 substituteHashmap(or any other abstract data type, such asConcurrentHashMap<K,V>) forHashtable.Open-Closed Principle
If you were feeling especially generous with your time you could go as far as:
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.