SSS 2.1 – Huntsville 2/22/14 Carol Yarbrough Alabama School of Fine Arts Arrays
What is an array? Sometimes we think of as a primitive – but is really an Object of type type[] An array inherits from Object 11 methods (equals, toString, …) equals & toString are NOT overriden !!
Advantages Can store: Primitives / arrays Object references More efficient than ArrayList when using primitives Uses less storage due to lack of overhead Can have multi-dimensional arrays int[][] m = new int[2][3]; Creates an array of length 2. Each entry is an array of 3 ints. m[i][j] is an int m[i] is an int[]
Disadvantages can’t be resized have to copy into a new array Hard to insert or remove in middle of array
Defining Arrays public class arrayExample { private char[] A = { 't', 'p', 'd', 'a', 'm' }; private String[] B; public arrayExample() { B = new String[5]; B[0] = "tomato"; B[1] = "pear"; B[2] = "durian"; B[3] = "apple"; B[4] = "mango"; }
Populating Arrays private int[] card = new int[10]; // refer to element by index card[0] = 4; card[i] = 995;
Accessing private int[] card = new int[10]; // refer to element by index int firstCard = card[0]; int newCard = card[i]; Finding Length int clen = card.length;
Array Traversals
For Loop, While Loop, For Each Loop? Could you do this with a for-each loop?
Where For Each Loop is Used int [] rolls = new int[10]; for(int i = 0; i < rolls.length ; i++) rolls[i] = (int) (Math.random() * 6) + 1; int sumRolls = 0; for (int r : rolls) { sumRolls = sumRolls + r; } Remember r is a reference, not an index. Can not change reference in for each loop.
For Each Loop Can’t be used to change array object! int[] a = {1, 2, 3}; for (int v : a) v = 6;// Does not change // values in array a. NOTE: v is a reference value, not an index ! Can be used to mutate referenced objects! Bug[] bugs = {new Bug(), new Bug(), new Bug()}; for (Bug b : bugs) b.setColor(Color.GREEN);// bugs now green
Copy Elements From One Array to Another
Circular Traversal of an Array
Work the Multiple Choice Questions in Your Student Packet
Multiple Choice Answers 1.C 2.E 3.B 4.D 5.D 6.E
Sample Free Response
Sample Free Response Solutions Part A private int getChargingCost(int startHour, int chargeTime) { int cost = 0; int index = startHour; for (int k = 1; k <= chargeTime; k++) { cost += rateTable[index]; index = (index + 1) % rateTable.length; } return cost; }
Part B public int getChargeStartTime(int chargeTime) { int startTime = 0; int minCost = getChargingCost(startTime, chargeTime); for (int k = 1; k < rateTable.length; k++) { int cost = getChargingCost(k, chargeTime); if (cost < minCost) { startTime = k; minCost = cost; } return startTime; }