title: Self-growing array java
body: <p>The question is to implement the three methods <code>get(int index)</code>, <code>set(intindex)</code>, and the constructor <code>SelfGrowingArray()</code> in order to produce the sentences shown in the main method. While it compiles, I get an <code>ArrayIndexOutofBoundsException</code>, specifically, this error:</p>
  
  <pre><code>[null, null, null, null, null, null, null, null, null, null, null, null, null, null, You don't know you're beautiful]
  [null, null, null, null, null, null, null, null, null, null, null, null, null, null, You don't know you're beautiful, null, null, null, null, null, null, What doesn't kill you makes you stronger.]
  Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -14
  </code></pre>
  
  <p>Here is my code, please help:</p>
  
  <pre><code>public class SelfGrowingArray {
  
  private Object[] data;
  
  public SelfGrowingArray()
  {
      data = new Object[0];
  }
  
  public void set(int index, Object value)
  {
      if (index &gt;= data.length) {
          Object[] newArray = new Object[index + 1];
          for (int i = 0; i &lt; data.length; i++) {
          newArray[i] = data[i];
          }
          data = newArray;
          }
          data[index] = value;    
  }
  
  public Object get(int index)
  {
      if (index &gt;= data.length)
      return null;
      return data[index];
  }
  
  public String toString()
  {
      if (data == null)
      {
          return "null";
      }
  
      int iMax = data.length - 1;
      if (iMax == -1)
      {
          return "[]";
      }
  
      StringBuilder b = new StringBuilder();
      b.append('[');
      for (int i = 0; ; i++)
      {
          b.append(data[i]);
          if (i == iMax)
          {
              return b.append(']').toString();
          }
          b.append(", ");
      }
  }
  
  public static void main(String[] args) {
      SelfGrowingArray myList = new SelfGrowingArray();
      myList.set(14, "You don't know you're beautiful");
      System.out.println(myList);
  
      myList.set(21, "What doesn't kill you makes you stronger.");
      System.out.println(myList);
  
      System.out.println("myList.get(-14) " + myList.get(-14));
      System.out.println("myList.get(14) " + myList.get(14));
      System.out.println("myList.get(15) " + myList.get(15));
      System.out.println("myList.get(31) " + myList.get(31));
      System.out.println("myList.get(32) " + myList.get(32));
  
  }
  }
  </code></pre>