Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 692265
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T02:37:58+00:00 2026-05-14T02:37:58+00:00

Consider the following Java source: if( agents != null ) { for( Iterator iter

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T02:37:59+00:00Added an answer on May 14, 2026 at 2:37 am

    Thread Safety

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

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

    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
        }
      }
    }
    

    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.

    Open-Closed Principle

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Consider the following two blocks of Java psedo-code in a system that uses optimistic
Consider the following code: java.util.Map<String, String> map = new java.util.HashMap<String, String>(); ... String key
Please consider the following java source: package com.stackoverflow; public class CondSpeed { private static
Consider the following Java code: volatile boolean v1 = false; volatile boolean v2 =
Consider the following two Java files that contain a simplified version of my issue
Consider the following piece of Java code. int N = 10; Object obj[] =
Consider the following directory structure: ./source/com/mypackage/../A.java ./extensions/extension1/source/com/mypackage/../T.java ./extensions/extension2/source/com/mypackage/../U.java ... ./extensions/extensionN/source/com/mypackage/../Z.java I want to produce
Consider the following Java code: Object a = new Integer(2); Object b = new
Let's consider the following code in Java. package obj; final class First { public
Consider the following two segments of code in Java, Integer x=new Integer(100); Integer y=x;

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.