// APS101, Winter 2009: Lecture 26 (Mar. 16) // // Review: last time we started writing the Pizza class as an example of how we can use 1-D arrays. Pizza p = new Pizza(3, "medium"); p.toString() p // automatically displays the output of the toString() method! p.addTopping("pineapple") p p.addTopping("sardines") p p.addTopping("blue cheese") p p.addTopping("pepperoni") // doesn't add this one! why? p Pizza p = new Pizza(3, "medium"); p.addTopping("pepperoni") p p.addTopping("pepperoni") p p.addTopping("pepperoni") // unfortunately, can have duplicates. p // let's write one more method: removeTopping // how would we go about doing this? // // we could make the topping null, then fill the gap // with the last element, and make the last element null. // (or we could shift back the rest of the toppings to fill // the gap, but the order of the toppings doesn't matter, so why make it slow?) // For example, if we have: // p = ["pineapple", "pepperoni", "anchovies"] // We want to remove "pineapple". // p = [null, pepperoni, anchovies] // Then, we want to fill the null gap with anchovies. // p = [anchovies, pepperoni, anchovies] // Finally, we want to make the last element null. // p = [anchovies, pepperoni, null] (take a look at the removeTopping(String t) method in Pizza.java) Pizza p = new Pizza(3, "small") p p.removeTopping("pepperoni") // nothing happens! p.addTopping("pepperoni") p p.removeTopping("pineapple") // nothing happens again! p p.addTopping("anchovies") p.addTopping("pineapple") p p.removeTopping("pineapple") // remove last-added topping p p.addTopping("pineapple") p p.removeTopping("pepperoni") // remove first topping p // 2-Dimensional Arrays int[] a = new int[3] int[][] b; b b = new int[2][3]; b b[1][2] = 123; b b.length b[0].length b[1].length b[2].length // error! // b is a 2-D (2-dimensional) array // b has 2 rows, 3 columns: 6 elements // A 2-D array is an "array of arrays" int[][] c = [3][]; int[][] c = new int[3][]; c c[0] = new int[5]; c c[1] = new int[3]; // can have different column lengths! c c[0].length c[1].length