AP Computer Science A / Chapter 4
Data Collections
Cheat sheet
Data and people
- Consider linkage through retained identifiers, locations and times. Aggregating to the needed measure and limiting access reduce personal exposure.
- Check accuracy, completeness, population and collection period before extending a conclusion. A missing value is different from an observed zero; systematic program errors can unfairly disadvantage groups.
Choose retained state
- A record count adds one per match; a quantity total adds the matching measurement. A conditional mean needs both a matching total and matching count, with a defined no-match result.
- An extremum candidate may start with an included value or a valid bound for the input domain, such as Integer.MIN_VALUE for an int maximum. Counts start at zero, existential flags at false and universal flags at true.
Array storage
- An array’s element type and length are fixed by its creation. Numeric elements start at zero, booleans false and references null; a reference array does not construct its element objects.
- Use array.length and indices from zero through length minus one. Assignment between array variables shares a reference; replacing one variable does not resize the shared array.
Traversal targets
- Indexed traversal controls the starting position, bound, direction and stride. An indexed array assignment or list set replaces stored elements.
- An enhanced variable receives a copy of a primitive or reference. Reassigning it does not replace collection storage; a copied reference can still mutate its object.
Relationships and order
- Adjacent array or list pairs use i and i+1 below the final position. All unordered distinct pairs use i<j; self-comparison is not evidence of duplication.
- String content comparisons use equals. A rightward copy proceeds from higher destinations downward; a leftward copy proceeds upward to preserve sources.
- Rotation retains the displaced endpoint, shift discards it under a stated fill rule, and reversal exchanges each symmetric pair once.
File input
- File represents a pathname; Scanner connected to that File reads input. Declare a checked opening failure with throws IOException or handle it. A declaration does not repair the input path.
- hasNext tests token presence without consuming it. nextInt, nextDouble and nextBoolean also require matching token syntax. Close the Scanner when reading is finished.
- Read a complete line for line records, split on the stated delimiter, select its zero-indexed fields and parse numeric fields separately.
Wrappers and parsing
- Integer and Double are immutable reference types. Arithmetic can unbox their values and box new results; a retained alias keeps the old value.
- Unboxing a null wrapper throws NullPointerException. Integer.parseInt and Double.parseDouble interpret valid numeric text rather than cast a String; invalid syntax fails.
ArrayList operations
- Construct an empty ArrayList with a reference element type such as Integer. size() counts current elements; get and set require an index below size.
- add(element) appends, add(index,element) inserts and admits index equal to size. set returns the replaced value without growth; indexed remove returns the removed value and shifts later entries left.
- For forward removal, retain the current index after deletion and recheck the shifted-in entry. Backward indexed deletion keeps unvisited positions stable. Avoid structural changes during enhanced traversal.
Rectangular matrices
- A 2D array contains row-array references. grid.length counts rows; grid[r].length counts columns in row r. One bracket selects a row, and a second selects its cell.
- Row-major order keeps the row index outside and column index inside. Column-major order reverses that nesting while retaining each index’s own dimensional bound.
- Reset a per-row summary at each row’s start; a whole-grid summary retains its state across rows. Horizontal neighbors share a row; vertical neighbors share a column.
Search
- Linear search can inspect unsorted input. Direction and immediate return versus continued candidate updates determine which duplicate index is reported. Place whole-collection failure after every relevant position has failed.
- Binary search needs sorted input. With inclusive bounds, move low to mid+1 or high to mid-1 after a failed comparison; exclude the tested midpoint to guarantee progress.
Sort passes
- Selection sort finds a suffix extremum and swaps it into a final boundary position. Its completed prefix is in final sorted positions.
- Insertion sort saves the next entry, shifts larger prefix entries and fills the resulting gap. Its completed prefix is relatively sorted but can move when smaller values arrive.
- Merge sort divides into smaller regions until base cases, recursively sorts the halves and merges their unconsumed fronts into one ordered result.
Recursive execution
- A reachable base case ends recursion. Each call retains independent locals while its child runs; pending expressions finish as callers resume.
- Invocation count includes the initial call, internal calls and base calls. It is distinct from the returned numerical value.
- A collection traversal tests its base boundary before indexed access. An iterative equivalent preserves the same base contribution, visited arguments and per-call combination.