name: inverse layout: true class: taylor msoe --- class: center, middle .title[ # Arrays and ArrayLists Review ] ??? Toggle speaker view by pressing P Pressing C clones the slideshow view, which is the view to put on the projector if you're using speaker view. Press ? to toggle keyboard commands help. --- # Arrays * An array allows us to refer to multiple values using one variable name -- * `int[] nums` — declares a variable `nums` that is a reference to an array of `int`s -- * `nums = new int[3]` — creates an array of three `int`s and assigns `nums` to point to it -- * The length of the array is fixed at creation time (not resizable) -- * `String[] weekdays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};` -- + Can have arrays of references -- + Can populate array at declaration with an array literal: `{value1, value2, ..., valueN}` -- + Can only use array literal when declaring an array --- # Accessing elements * `nums[0]` accesses the first element of the array -- * `nums[i]` accesses the (i+1)
st
element -- * `nums[i]` can appear on both sides of an assignment operator ``` int value = nums[2]; nums[0] = value; ``` -- * The size of the array is obtained from the `length` **attribute** ``` // shifts all elements one element forward for(int i=0; i
words = new ArrayList<>(); ``` -- * The generic provides **type safety** — only allows correct type of objects to be added to the list --- # Common Methods * `boolean isEmpty()` -- * `E get(int index)` -- * `E set(int index, E element)` — returns what used to be at the position -- * `boolean add(E element)` — always returns `true` -- * `void add(int index, E element)` — shifts elements to the right to make room -- * `E remove(int index)` — shifts elements to the left to fill empty space -- * `boolean remove(Object target)` — removes first match, if found and returns `true` if list is changed --- # Additional Common Methods * `int size()` -- * `int indexOf(Object target)` — index of first match starting at the beginning of the list -- * `int lastIndexOf(Object element)` — index of first match starting at the end of the list -- * `boolean contains(Object element)` --- # Enhanced `for` Loop * Also know as, for-each loop * Alternative syntax exists for in-order traversing all elements in a list ``` public static double max(ArrayList
nums) { double max = Double.NEGATIVE_INFINITY; for(Double num : nums) { max = Math.max(max, num); } return max; } ``` -- ``` public static double max(ArrayList
nums) { double max = Double.NEGATIVE_INFINITY; for(int i=0; i