Integer[] a = new Integer[2]; //Add an element a[0] = 10; //Add an element a[1] = 20; int n = a[1];
Integer[] a = new Integer[2]; //Add an element a[0] = 10; //Add an element a[1] = 20; //Add an element a[2] = 30;
-- Recipe for "append(newElement)" -- -- or "add(newElement)" 1. If !hasCapacity() grow() 2. elements[size] = newElement 3. size++
size < capacity
-- Recipe for "grow" -- //note: we "round" product to nearest integer 1. newCapacity = round(existingCapacity * growthFactor) 2. newArray = constructNewArray(newCapacity) 3. copyElementsInto(newArray) 4. this.elements = newArray We partition the work to simplify. Steps #1 and #3 are simple, let us look at #2. -- Recipe for "copyElementsInto(newArray)" //Let us call the loop variable "index" Iterate from 0 to (size - 1) element = get element at index put element into newArray at index index++
-- Recipe for "insert(index, newElement)" -- 1. If index is not valid (0 to size) throw exception 2. If !hasCapacity() grow() 3. shiftRightFrom(index) 4. elements[index] = newElement 5. size++ -- Recipe for "shiftRightFrom(shiftStartIndex) -- //shiftStartIndex is where we start the shift //We work backwards from end (do you know why?) //Let us call the loop variable "i" Iterate from size down to shiftStartIndex element = get element at (i-1) put element into newArray at i i--