title: How to prevent infinite recursion loop
body: <p>I can't seem to come up with a solution to my recursion problem. So I have this Version object that holds a list of references to other version objects it is dependent on.</p>
  
  <p>Version</p>
  
  <pre><code>{
    "id": "id1",
    "version": "1",
    "dependencies": [
      {
        "id": "id2"
      },
      {
        "id": "id3"
      }
    ]
  }
  </code></pre>
  
  <p>When I retrieve this object I also have to retrieve it's dependencies as well the dependency's dependencies until there is an eventual end, which would look something like this</p>
  
  <p>VersionDto</p>
  
  <pre><code>{
    "id": "id1",
    "version": "1",
    "dependencies": [
      {
        "id": "id2",
        "version": "2",
        "dependencies": [
          {
            "id": "id4",
            "version": "4",
            "dependencies": []
          }
        ]
      },
      {
        "id": "id3",
        "version": "3",
        "dependencies": []
      }
    ]
  }
  </code></pre>
  
  <p>This is my Recursive function to retrieve a version</p>
  
  <pre><code>public VersionDto getVersion(String id)
  {
      //Retrieves from database
      Version version = versionDAO.getVersion(id);
  
      //Convert to Dto (basic fields)
      VersionDto versionDto = new VersionDto(version);
  
      //Recursivly retrieve dependencies 
      for (Map&lt;String, String&gt; dep : version.getDependencies()) {
          VersionDto dto = new VersionDto();
  
          //Recursive call
          dto = getVersion(dep.get("id"));
          versionDto.getDependencies().add(dto);
      }
  
      return versionDto;
  }
  </code></pre>
  
  <p>However I run into the problem of a possible infinite loop in the case where a version could be a dependency to one of the nested dependencies such that v1 -> v2 -> v4 -> v1 causing a infinite repeat.</p>
  
  <p>Any idea how I could solve and prevent this infinite loop, so that if the version all ready occurred earlier it should just skip it? </p>
  
  <p><strong>Edit: Solution using global list</strong></p>
  
  <pre><code>public VersionDto getVersion(String id)
  {
  
      //Check global list contains version
      if (visited.contains(id)) {
          return null;
      }
  
      visited.add(docId);
  
      //Retrieves from database
      Version version = versionDAO.getVersion(id);
  
      //Convert to Dto (basic fields)
      VersionDto versionDto = new VersionDto(version);
  
      //Recursivly retrieve dependencies 
      for (Map&lt;String, String&gt; dep : version.getDependencies()) {
          VersionDto dto = new VersionDto();
  
          //Recursive call
          dto = getVersion(dep.get("id"));
          if(dep!= null) {
          versionDto.getDependencies().add(dto);
          }
      }
  
      return versionDto;
  }
  </code></pre>