title: How to depth first search through a collection of objects using recursion?
body: <p>The depth first search method I'm using to find a particular location by it's ID field, throws a Null pointer exception when looping through a list of location objects.</p>
  
  <p>I debugged the error by setting a breakpoint on the <code>findLocation()</code> and <code>dfs()</code>, and it only fires the NPE in the <code>dfs()</code> for loop. So for example if I specify a location id of '1' the location will be returned correctly, but if I specify a location ID greater than 1 I get an NPE when the code steps into the <code>dfs()</code> for loop.</p>
  
  <p>Does anyone know why the <code>for</code> loop is giving an NPE on any location ID greater than 1?, although the location ID's range from 1 - 10.</p>
  
  <p>These are the two methods used in conjunction to find a location by ID:</p>
  
  <pre><code>public Location findLocation(Integer locationId) {
          Location result = null;
          for (Location l : location) {
              System.out.println("In find method...");
              result = dfs(new HashSet&lt;Location&gt;(), l, locationId); //line 180
              if (result != null)
                  System.out.println("You are now in.." + result);
                  break;
          }
          return result;
      }
  
  
  private Location dfs(Set&lt;Location&gt; visitedAlready, Location current,
              Integer id) {
          if (current.id == id)
              return current;
          visitedAlready.add(current); 
          Location result = null;
          for (Location l : current.location) { //line 194
              result = dfs(visitedAlready, l, id);
              if (result != null)
                  break;
          }
          return result;
      }
  </code></pre>
  
  <p>The exact error that is output is the following:</p>
  
  <pre><code>Exception in thread "main" java.lang.NullPointerException
      at gmit.Location.dfs(Location.java:194)
      at gmit.Location.findLocation(Location.java:180)
      at gmit.GameParser.parse(GameParser.java:55)
      at gmit.Main.main(Main.java:28)
  </code></pre>