matthewalangreen
4/19/2017 - 7:04 PM

AddArrayElement


public void add(int index, int element)
    {
      // good idea, but not needed.  No new array is necessary
      int[] newArray = new int[currentSize+1];

      int length=currentSize+1;
      for(int i=0;i<index;i++)
      {
          newArray[i]=arr[i];
      }

      newArray[index] = element;

      for(int i = index+1;i<length;i++)
    {
        newArray[i]=arr[i-1];
    }
    arr=newArray;
    }

    // it looks to me like you did this:
    // 1. make a new array that is size one larger than previous --LINE 5
    // 2. copy all elements from old array into new one, up to "index" -- LINES 7-11
    // 3. add new element at index -- LINE 13
    // 4. Copy the rest of the items from old array into new one -- LINES 15-20




    // I did the following.  Maybe you can try my method?
    // I'm doing something similar with what i did with the remove(int index) method
    // because of how ExpandingArray is built... we know we won't run out of space
    // so...
    // 1. start at item index, move all elements from index to the End
    //    one space to the right
    // 2. add the new item at the index
    // 3. increment numElements