Index
Video 📹


Video accompanying this page...

Our Plan


Impossible Problem?
  • We want a fixed array (speed)
  • We don't want a fixed array (inflexible)

A bit of a paradox
??
An Idea
What about an object, that we'll call a "DynamicArray", that holds a fixed array under the hood (i.e. as "ivar")?

  • Thus we're half done -- fast indexed access maintained
  • We need to figure out how DynamicArray could allow adding and removing elements

Trick is Extra Capacity


If we have a fixed array extra capacity, then we would have space to e.g. append a new element.

Our next "append" of an actual element would go into the first blank slot.
The blank slots might be nulls, but we don't really care. We don't use them for anything.

We will not access and return them. We will only return "actual elements" to our object user.
  • capacity -- total length of the fixed array (10)
  • size -- count of actual elements (6)

We have extra capacity of 4

Initial Object Diagram


Object Diagram
We can see that we'll need to have these available to our logic: "capacity" and "size".

We can derive "capacity" from the our "elements" component.

We'll need to keep track of "size". We'll need a simple (integer) component for that called "size".

Public vs Private Array Areas


Examples


We really want to understand capacity well so here is another perspective.

We will use the dynamic array by sending messages to it like get, subList, first, last, etc.

All of these public methods only apply to the "Public Data"
  • get(0) is 10
  • get(1) is 20
  • get(2) is 30
  • get(3) is 40
  • get(4) is an EXCEPTION -- out of bounds

Access is from 0 to (size-1)
Here is a case where we have no elements (size = 0).

We could not do any access methods like get, first, last, etc. There is no pubic data.
We are about to remove element 20.
We need to do some shifting to remove the removed slot in the accessible zone.