title: ArrayList vs Doubling Array Size?
body: <p>So a common programming practice for when an array can't hold the amount of information we want it to, is to double the size of an array.  We do this by creating a new array, with double the original arrays size, populating this new array with the old values, and setting it as the old array.
  Here's a example in Java:</p>
  
  <pre><code>public int[] doubleArray(int[] old) {
      int[] doubled = new int[old.length * 2];
      for (int i = 0; i &lt; old.length; i++) {
          doubled[i] = old[i];
      }
      return doubled;
  }
  </code></pre>
  
  <p>So is it more <em>better</em> to use a standard array and double the size, when needed, or to simply use an ArrayList (which changes its own size based on the input you give it by 1)?  Basically, is it better to double an arrays size when you need to store more than the array allows, or to increase its size by 1 each time?  And what would be the limit to which one becomes a better choice than the other?</p>
  
  <p>If I had to guess, using a standard array <em>should</em> be faster, given that it's in the <code>java.lang</code>, so I made the following class to test my theory:</p>
  
  <pre><code>public class ArrayTesting {
      public static void main(String[] args) {
      long startTime1 = System.nanoTime();
      int[] ints = new int[10];
      for (int i = 0; i &lt; ints.length; i++) {
        ints[i] = i * 2;
      }
      long timeToSetOriginalValues = (System.nanoTime() - startTime1);
      long startTime2 = System.nanoTime();
      ints = doubleArray(ints);
      long timeToDouble = (System.nanoTime() - startTime2);
      long startTime3 = System.nanoTime();
      for (int i = 9; i &lt; ints.length; i++) {
        ints[i] = i * 2;
      }
      long timeToSetNewValues = (System.nanoTime() - startTime3);
      System.out.println("Set Values in " + timeToSetOriginalValues);
      System.out.println("Doubled Array in " + timeToDouble);
      System.out.println("Finished setting values in " + timeToSetNewValues);
      System.out.println("Total time: " + (timeToSetOriginalValues + timeToDouble + timeToSetNewValues));
    }
  
    public static int[] doubleArray(int[] old) {
      int[] doubled = new int[old.length * 2];
      for (int i = 0; i &lt; old.length; i++) {
        doubled[i] = old[i];
      }
      return doubled;
    }
  }
  </code></pre>
  
  <p>But for an unknown reason, I am getting extremely varying results.  Varying total time from everything between 11,000 and 4,000.  Assuming it's something I did wrong, is there someone better at timing who could answer my question?</p>