Arrays
Initializing
- Arrays are initialized by default:
int[] array = new int[10]gives an array full of ten0s- What does
boolean[] array = new boolean[15]give? - How about
String[] array = new String[22]?
Storing partial results
- How would you write a method
daysInMonth(int month, int year)?- How could an array help?
- How would you write
ordinalDate()? - How could a
DAYS_IN_MONTHarray help? - How could a different array let you remove the loop?
parallel arrays
- Look at a standard description of tax brackets: https://www.debt.org/tax/brackets/
- How could you write a
calculateTax(income)method without using a loop (or explicitly calculating the tax for each bracket)?970 + .12 (income - 9700);4543 + .22*(income - 39475)- https://turbotax.intuit.com/tax-tips/irs-tax-return/current-federal-tax-rate-schedules/L7Bjs1EAD
- We could create a
Taxobject withmaxandratefields. Or we can just have two parallel arrays.
- How could you write a
- Sometimes having two arrays is easier than creating separate objects.
Using an array to store counts
- Write a method
int mode(int[] nums)that returns the number that occurs most frequently. - How many loops does your code have?
- Can you use only one loop?
Two-dimensional arrays
- A matrix (2D grid) can be represented as a 2D array:
int[][] matrix = new int[5][7]generates a grid with 5 rows and 7 columns.- Just use both indices to access:
matrix[3][4] = 14
- That’s the easy case. We need to peek under the hood:
-
A 2D array is an array of arrays. Saying
new int[rows][cols]is really a short-cut forint[][] matrix = new int[numRows] for (int row = 0; row < numRows; ++row) { int[row] = new int[numCols]; } - Each row in an array is a complete, separate Java object.
- With this “array of array” model, we can access the dimensions of the array like this:
int numRows = matrix.length;int numCols = matrix[0].length(this works if all rows have the same number of columns)
- Because each row is a separate Java object, rows don’t have to all have the same number of columns.
- This is called a “jagged” array.
- Jagged arrays aren’t terribly common.
- Most common scenario is probably representing only half of a symmetric matrix.
- Consider a matrix representing people in a room.
friends[r][c]istrueof personrand personcknow each other. This matrix is symmetric. Thus, we need only store half of it.
- Consider a matrix representing people in a room.