Student: OK, so we can make collections of strings. I’m not impressed.
Prof: Oh?
Student: I started this conversation wanting to make big collections of like, lots of images or course rosters like you keep suggesting.
Prof: I see, that makes sense. Let me think of a good first example… OK how about this. We’ll have a class that stores an array of points, representing a bunch of positions on a coordinate plane. In, say, sports analytics, this could be positions of players on a field. In a physics experiment, it could be positions of particles.
Student: OK, so now you’ve used
Point[] as the type of a field?Prof: That’s right. Why don’t you try constructing some example points and a
Positions instance?Student: Sure.
Student: Huh, that didn’t work. Why not?
Prof: How many fields does
Positions have?Student: Three?
Prof: Setting aside your example for a minute, just look at
record Positions(Point[] points). How many fields?Student: Oh, just one. Ohhhh so I have to make an array and give just one array to the constructor? Like this:
Prof: You got it. OK so let’s think of some interesting methods to write for
Positions. Can you think of any?Student: Um… maybe like which points are the closest to each other or furthest?
Prof: Great. Let’s do “which point is closest to a given point”, how about that? That could make sense for a lot of tasks, like which player is closest to a goal, or which particle is closest to some stimulus in an experiment.
Student: Sure, I buy that.
Prof: Let’s assume
Point defines double distanceTo(Point other); we’ve seen things like that before, and focus on this new method in the Positions record. What do you think the method header looks like?Student: OK, I need a name and the arguments. So probably the name is like
closestTo and then the argument is a Point?Prof: And you need one more thing – the return type.
Student: Oh, probably it returns a point, like the one it found that is closest.
Prof: Great. What’s a good placeholder value for the method?
Student: Maybe just like… the first point in the array?
Prof: Sure – go ahead and let’s get that in. Maybe at the same time write a few examples of calling it with comments for what you expect?
Prof: Excellent! So both of these are always returning the 3.0, 4.0 point for now because that’s the first one. Now we need to fill it in.
Student: Awesome!
Practice
Make
order a PizzaOrder that holds both pizzas: fill in the type of the pizzas field, define an array of the pizzas on the empty line, and pass it to the constructor.record Pizza(double inches, int costCents) { }
record PizzaOrder( pizzas) { }
Pizza big = new Pizza(16, 1000);
Pizza small = new Pizza(10, 500);
PizzaOrder order = new PizzaOrder();
record PizzaOrder( pizzas) { }
Pizza big = new Pizza(16, 1000);
Pizza small = new Pizza(10, 500);
PizzaOrder order = new PizzaOrder();