Array
What are the essential properties of a Java array? An array is an ordered, zero-indexed collection of one type. Its physical size is fixed after creation, it can store primitives or object references, and valid indexes are 0 through arr.length-1.
For int[] arr = new int[5];, what are the length, valid indexes, and default values? Length = 5; valid indexes = 0–4; every int starts as 0. GOTCHA: arr[arr.length] means arr[5] and is out of bounds.
What default values are placed in newly created primitive and reference arrays? An int array starts with 0s; a String/reference array starts with nulls. Example: new int[4] → four 0s; new String[4] → four nulls.
What is the difference between int[] a, b; and int a[], b;? int[] a, b; makes BOTH variables arrays. int a[], b; makes a an int[] but b a normal int. Bracket placement matters when several variables are declared together.
How does an array initializer list work? int[] coins = {1,5,10,25}; creates and initializes the array, and Java determines its length. GOTCHA: do not combine a specified size with this initializer-list form.
Why can an array's values change even though its size cannot? The array object has a fixed number of positions after creation, but the values stored in those positions can be reassigned. Fixed size does NOT mean the elements are unchangeable.
What is array aliasing? int[] b = a; copies the reference, not the array. Both variables point to the same array object, so a change through b is visible through a.
Trace: int[] a={1,2,3}; int[] b=a; b[0]=9; System.out.println(a[0]); 9. a and b are aliases for the same array, so changing b[0] changes the one shared array.
Trace: int[] x={1,2,3}; int[] y={1,2,3}; System.out.println((x==y)+" "+(x[0]==y[0])); false true. x==y compares array references, which are different objects. x[0]==y[0] compares primitive int values, both 1.
What does traversing an array mean? Visiting every element, usually with for (int i=0; i<arr.length; i++) or an enhanced for loop when the index is unnecessary.
Why does for (int x : arr) { x *= 2; } NOT modify an int array? x is a copy of each primitive element. Reassigning x does not write back to arr. To modify elements, use an indexed loop such as arr[i] *= 2.
When is an enhanced for loop a good choice for an array? When you only need each value, such as summing, counting, or checking conditions. Use an indexed loop when you need indexes or need to replace array elements.
What is the standard pattern for summing all values in an array? Initialize sum = 0, traverse every element, and add each value. Example: for (int v : arr) sum += v;.
What is the standard pattern for counting occurrences of a target? Start count = 0; traverse the array; whenever an element equals the target, increment count. Example: if (arr[i] == target) count++;.
What is the standard pattern for testing whether a target is present? Search until the target is found; then set a boolean/return immediately. If the search ends with no match, report not found. A common index sentinel is -1.
How do you efficiently find the LAST occurrence of a target? Search backward from arr.length-1. The first match encountered from the right is the last occurrence. If no match exists, return -1.
Trace: findLast({4,7,4,2,7}, 7) where the loop searches backward. Returns 4. The backward search encounters the 7 at index 4 before the earlier 7 at index 1.
Why must a loop comparing arr[i] with arr[i+1] use i < arr.length-1? Because i+1 must remain a valid index. If i reaches the last index, arr[i+1] would access arr[arr.length], which is out of bounds.
What does this code count? if (arr[i] > arr[i+1]) count++; It counts adjacent decreases, or descents. For {5,3,8,6,2,9}, the descents are 5>3, 8>6, and 6>2, so count = 3.
Trace this mutation: {3,8,1,9,4} with arr[i] = arr[i] + arr[i-1] from left to right. Final array: {3,11,12,21,25}. GOTCHA: each iteration uses the ALREADY MODIFIED previous element, creating a running cumulative sum.
Why can modifying an array during traversal change later calculations? Later iterations may read values changed by earlier iterations. When tracing code, always ask whether an expression is using an original value or an already-updated value.
What does saving arr[0], shifting all elements left, then putting the saved value at the end accomplish? A left rotation by one position. Example: {1,2,3,4,5} becomes {2,3,4,5,1}. Saving the first element prevents it from being overwritten.
Why is int max = 0; unsafe when finding the maximum of an arbitrary nonempty int array? If every array value is negative, 0 incorrectly remains max even though 0 is not in the array. Safer initialization: int max = arr[0];.
What is the correct AP pattern for checking whether EVERY element satisfies a condition? Return false immediately when one violating value is found; return true only after the entire loop completes. One failure disproves “all,” but one success does not prove it.
How should allPositive(int[] arr) work? For every value v, if v <= 0, return false immediately. If the entire traversal finishes without finding one, return true.
What is the integer-division trap when calculating an array average? sum / nums.length performs integer division if both operands are ints. Use (double) sum / nums.length to preserve the fractional part.
What are an array's physical size and logical size? Physical size = allocated positions, arr.length. Logical size = how many positions are currently considered meaningful/used, usually tracked in a separate variable.
An array has length 1000 but only the first 50 entries are being used. What are its physical and logical sizes? Physical size = 1000; logical size = 50. The physical size remains fixed while the logical size can increase or decrease.
How do you safely add an element to an array that uses logical size lsize? if (lsize < arr.length) { arr[lsize] = value; lsize++; } The logical size points to the first unused position.
How do you logically remove the final used element from a fixed-size array? Decrease the logical size: lsize--;. The physical array does not shrink; the program simply stops considering that final position part of the logical data.
How do you remove a logical element from the middle of a fixed-size array? Shift later logical elements one position left to cover the removed value, then decrement logical size. The underlying physical array length stays unchanged.
What are the major differences between an array and an ArrayList? Array: fixed size, can store primitives, uses arr[i] and arr.length. ArrayList: resizable, stores objects, and uses methods such as get, set, add, remove, and size().
Where does ArrayList fit in the Java Collections material shown in class? ArrayList is a type of List within the Java Collections hierarchy. The class diagram also shows other collection categories such as Set and Queue.
Why is ArrayList<int> invalid but ArrayList<Integer> valid? ArrayList stores objects, not primitive types. Integer is the wrapper class for int. Similarly: double→Double and boolean→Boolean.
What is autoboxing? Java automatically converts a primitive into its wrapper object when needed. Example: adding int 7 to an ArrayList<Integer> automatically wraps it as an Integer.
What are the three easy-to-confuse size/length expressions? Array → arr.length; String → str.length(); ArrayList → list.size(). GOTCHA: only array .length has no parentheses.
What does list.add(value) do? Appends value to the end of the ArrayList and increases its size by 1.
What does list.add(index,value) do? INSERTS the value at that index. The existing element at that index and all later elements shift RIGHT, and the list size increases by 1.
What does list.set(index,value) do? REPLACES the element at that index without changing list size. It returns the OLD element that was replaced.
What does list.get(index) do? Returns the element currently stored at that index without changing the ArrayList.
What does list.remove(index) do? Removes and RETURNS the element at that index. Every later element shifts LEFT by one, and list size decreases by 1.
Trace: list is [A,B]; then add(0,"C"); add(1,"D");. What is the final list? [C,D,A,B]. First insertion makes [C,A,B]; inserting D at index 1 shifts A and B right.
Trace: [10,20,30,40]; int x=list.remove(1); int y=list.set(1,5);. Find x, y, and the final list. x=20, y=30, final list[10,5,40]. remove returns the removed 20; after shifting, set replaces 30 and returns that old value.
Trace: [Sheldon,Mickey,Raj,Howard]; execute list.add(0, list.remove(list.size()-1));. [Howard,Sheldon,Mickey,Raj]. Evaluate inside-out: remove the last element and return Howard, then insert that returned value at index 0.
Why is remove(1) tricky in an ArrayList<Integer>? In the remove(int index) form used here, 1 means INDEX 1. Example: [5,3,1] → remove(1) removes 3, leaving [5,1].
What is the major gotcha when removing from an ArrayList while traversing forward? Removal shifts later elements LEFT. The next element moves into the just-removed index, but the loop may increment i and skip that shifted element.
Trace the skipping bug: [2,4,4,5,6]; forward loop removes nums.get(i) whenever it is even. Final result: [4,5], not [5]. After removal, a new element shifts into index i; then i++ skips it. This is the classic forward-removal bug.
Why can adjacent duplicate targets be missed during forward removal? If the first target is removed, the second target shifts into the same index. The loop then increments past that index, so the shifted duplicate is never tested.
What are the THREE safe strategies from the class material for removing multiple matching ArrayList elements? 1) Forward for-loop and decrement i after removal. 2) While-loop that increments only when no removal occurs. 3) Traverse backward from size()-1 to 0.
Why is backward traversal usually the simplest strategy for repeated ArrayList removal? Removing index i shifts only elements with larger indexes. In a backward loop, those larger indexes have already been processed, so no unprocessed element is skipped.
Why can storing the original ArrayList size before a removal loop be dangerous? The list becomes smaller but the stored size does not. Continuing to use the old count can eventually attempt to access an index that no longer exists.
What can happen if you add or remove elements from an ArrayList inside an enhanced for loop? A ConcurrentModificationException can occur. Enhanced for loops are not appropriate for structurally modifying the same ArrayList during traversal.
How should String contents be compared in array/ArrayList algorithms? Use .equals(), such as word.equals(target). GOTCHA: == compares object references rather than String contents.
How should countMatches(ArrayList<String> words, String target) work? Start count at 0, traverse every String, increment when w.equals(target), then return count. GOTCHA: using == instead of .equals() can give the wrong result.
How should removeShort(ArrayList<String> words, int minLen) be written safely? Traverse backward from words.size()-1 to 0. If words.get(i).length() < minLen, remove index i. Backward traversal avoids skipped elements.
How does an isSorted(int[] arr) method test for non-decreasing order? Compare each adjacent pair. If arr[i] > arr[i+1], return false immediately. If no violation is found, return true after the loop. Equal neighbors are allowed.
Why would isSorted be wrong if it returned true inside the loop after seeing one ordered pair? One correct pair does not prove the entire array is sorted. True can only be returned after every adjacent pair has been checked.
How do you create a reversed COPY of an array without changing the original? Create new int[arr.length]; for each i set result[i] = arr[arr.length-1-i]; return result. GOTCHA: int[] result = arr; creates an alias, not a copy.
Why is an ArrayList a good return type for a method collecting all scores above average? The number of qualifying scores is unknown until the data is examined. ArrayList can grow dynamically, while an array would require its length to be decided in advance.
How should aboveAverage(int[] scores) work conceptually? Compute the double average, create an empty ArrayList<Integer>, traverse scores in original order, add scores strictly greater than the average, and return the list.
Trace: aboveAverage({70,90,80,100}). Average = 85.0, so the result is [90,100]. GOTCHA: “above” means strictly greater; values equal to the average are excluded.
What does a sum of consecutive differences such as (arr[i]-arr[i-1]) simplify to? Interior values cancel, leaving last element minus first element. Example: (12-9)+(9-6)+(6-3)=12-3=9. This is a telescoping-sum code-reading pattern.
What exceptions should you recognize for bad indexes in this unit? Invalid array access can throw ArrayIndexOutOfBoundsException; invalid ArrayList method indexes can throw IndexOutOfBoundsException.
What happens when an indexed ArrayList add or remove occurs? add(index,x) shifts elements at that index and later RIGHT. remove(index) shifts later elements LEFT. Tracking these shifts is essential for code tracing.
What should you do first when tracing complicated ArrayList code? Rewrite the list after EVERY add, remove, or set; then recalculate indexes and size. Do not mentally keep using positions from before the mutation.
What should you do first when tracing complicated array code? Check loop bounds, aliases, and whether the array is being modified. If it is, determine whether later iterations use already-modified values.
What are the highest-value gotchas to know cold for this unit? Last index = length-1; aliasing; enhanced-for copies; mutation affecting later iterations; add vs set; remove/set return values; removal shifting; skipped elements; String .equals(); Integer vs int; integer division; safe i+1 bounds; and returning true only after checking all elements.
Sent from my Galaxy