☰ Contents Collecting Values

Making Arrays

Student: OK I’m liking these patterns. What are some other ones?
Prof: Great let’s keep going. Sometimes you want to take an array and produce a new array with a value calculated from each element of the original array. That requires some new thinking. An example is something like taking a roster of Student records and getting all their emails as a String array.
Student: OK, I can see that being useful.
Prof: Let’s set it up. A Student record and a CourseRoster record with an array of students
Student: OK, I see. So we’re going to try to write String[] emails(String domain)?
Prof: That’s right, and we need one more feature of arrays to handle it. The pattern here is called builder, and the new feature is changing an element of an array arr[i] = v where arr is an array and i is an integer. That’s called array update, and it’s how we make sure the null values are all replaced with the values we want before returning the new array.
Student: OK, so we make the array at the top, kind of like we initialized the totals or counters, and then we update in a loop?
Prof: Yup, that’s right. Like with numberedList, we combine it with a counter, so that we can refer to indices correctly. Here the counter is used as the index for the array update
Student: Interesting. So it returns the whole array.
Prof: Right. The new String[students.length] makes a brand new array, and the loop fills it in with string values from the results of the .email method.

Practice

areas should return a new array holding the area of each pizza in the order, in the same order. Fill in the three missing pieces.
record Pizza(double inches, int costCents) {
double area() {
double radius = inches / 2;
return radius * radius * Math.PI;
}
}
record PizzaOrder(Pizza[] pizzas) {
double[] areas() {
double[] result = ;
int index = 0;
for(Pizza p: pizzas) {
;
;
}
return result;
}
}
Pizza small = new Pizza(10, 500);
Pizza big = new Pizza(16, 1000);
Pizza medium = new Pizza(12, 900);
Pizza[] partyPizzas = { small, big, medium };
PizzaOrder party = new PizzaOrder(partyPizzas);
double[] partyAreas = party.areas();