Adding


Note: the operation "add" means to "append" an element to the end of the array.

Adding (Sufficient Capacity)


Let us say we have five extra capacity blank slots.

NOTE WELL:
size = 5
capacity = 10
To add, we simply put the new element into the first blank slot (immediately after the actual elements).

NOTE WELL -- you can determine the index to add the element using "size"
We now have one more "actual element" and one less "extra capacity"

NOTE WELL:
size = 6
capacity = 10


Adding (Insufficient Capacity)


No Extra Capacity
In this case, there is no capacity (slot) for the new element.

We're not able to add.
Two Helper Methods Needed
We need two helper methods:

  • hasCapacity - will answer true if there is sufficient capacity
  • grow - will add more capacity


Algorithm


Try to Devise an Algorithm for "Add"
First try to come up with an algorithm on your own.

If you get stuck or want to compare then click to show a solution.


-- Recipe for "add(newElement)" If we do not have enough capacity to add grow the capacity set "newElement" into first open (unused) slot (index position). Increment ?? Notes: 1. Replace "??" with something that should be incremented. Hint: See "Initial Object Diagram" in "Design". 2. This algo is high level (not detailed) on purpose -- so that you can have the fun of adding in details.