title: Instance variable in linked list
body: <p>I have written a program about patients. I have my own linked list collection class. <strong>I could have used Java's linked list but the idea of my program is to get practice and get to know more about how linked list works.</strong> </p>
  
  <p>Here is a code snippet of my program.</p>
  
  <pre><code>class PatientList {
   private PatientNode head;
   private int lastArrival;
   private int size;
  
   public PatientList() {
    head = null;
    lastArrival = 0;
    size = 0;
   }
  
   public void add(String name, int severity) {
    //PatientNode previous;
    Patient patient;
  
    lastArrival++;
    patient = new Patient(name, lastArrival, severity);
  
    head = new PatientNode(patient, head);
    size++;
   }
  </code></pre>
  
  <p>Now, my problem is with the <code>size</code> instance variable. I seem to get <code>0</code> no matter what. However when i try to calculate <code>size</code> in the <code>print</code> method i get the <code>size</code> value right. Here is my <code>print</code> method code:</p>
  
  <pre><code>public void print() {
   PatientNode current;
   //int size = 0;
  
   current = head;
   while (current != null) {
    System.out.println(current.data);
    //size++;
    current = current.next;
   }
  
   System.out.println("Size = " + size()); //size() method actually returns size.
   System.out.println("Last arrival = " + lastArrival);
  }
  </code></pre>
  
  <p>Can anyone point out what i am doing wrong when i am using instance variable? I just don't understand why would it print <code>0</code> when i am incrementing the <code>size</code> each time something is added to the list.</p>
  
  <p><strong>Edit</strong></p>
  
  <p>The size method is here in case that helps you help me solve the problem.</p>
  
  <pre><code>public int size() {
   return size;
  }
  </code></pre>
  
  <p><strong>Edit 2</strong></p>
  
  <pre><code>String[] names = { "Zelma", "Clayton", "Casper", "Ihor", "Edwina" };
  int[] severities = { 1, 2, 3, 1, 3 };
  PatientList list;
  
  list = new PatientList();
  testPatientList(list, names, severities, 0);
  }
  
  public static void testPatientList(PatientList list, String[] names, int[] severities, int pos) {
   PatientList copy;
  
   if (pos &lt; names.length) {
    list.add(names[pos], severities[pos]);
    copy = list.clone();
  
    copy.print();
    System.out.println("Admitting: " + copy.nextAdmission());
    System.out.println();
  
    testPatientList(list, names, severities, pos + 1);
    testPatientList(copy, names, severities, pos + 1);
    }
   }
  }
  </code></pre>