title: How to use recursive methods with lists
body: <p>I have a small problem with wrapping my head around how to use recursive methods to count the number of elements in a list, then jumping to each element in that list and count how many elements they have stored. I will try to generalize this as much as possible, but I will use an example of my own. 
  The data structure that I have, is an arraylist where I have stored elements. All of these each have an arraylist where the elements pointing to this element is stored by the preceding elements ID. So: Element->List->ID (Integer, ie. 2)-> Element nr.2. I want to count how many preceding elements there is for each element, by recursive methods. I have tried a couple of options, like storing all of the preceding elements in a new list and then give the size of this as the number of preceding elements, as well as using a counter-int. The closest I have gotten so far is using this method(id is a number always +1 the index it is located in the arraylist containing it):</p>
  
  <pre><code>private int getPredecessorCount(int id){
      for(int i:elementList[id-1].predecessors){
          return 1+getPredecessorCount(i);
      }
      return 0;
  }
  </code></pre>
  
  <p>This gives me correct answer for all the elements where the elements contains a list with only a single element. I cannot get it to work with the elements having lists with more than 1 predecessorelement. Any ideas? </p>
  
  <p>I also tried:</p>
  
  <pre><code>    private int getPredecessorCount(int id, int counter) {
      if(!elementList[id-1].predecessors.isEmpty()){
          for(int i : elementList[id-1].predecessors){
              counter+=getPredecessorCount(i, counter);
              counter++;
          }   
      }
      return counter;
  </code></pre>
  
  <p>This gives me somewhat the same result as the previous one, but where the previous one gave me too few predecessors for the ones who contained larger lists, this one gives me wildly too many. </p>